js原生函数bind

在javascript中,函数总是在一个特殊的上下文执行(称为执行上下文),如果你将一个对象的函数赋值给另外一个变量的话,这个函数的执行上下文就变为这个变量的上下文了。下面的一个例子能很好的说明这个问题
代码如下:

window.name = "the window object" 
function scopeTest() { 
return this.name; 
} 
// calling the function in global scope: 
scopeTest() 
// -> "the window object" 
var foo = { 
name: "the foo object!", 
otherScopeTest: function() { return this.name } 
}; 
foo.otherScopeTest();// -> "the foo object!" 
var foo_otherScopeTest = foo.otherScopeTest; 
foo_otherScopeTest(); 
// –> "the window object" 

如果你希望将一个对象的函数赋值给另外一个变量后,这个函数的执行上下文仍然为这个对象,那么就需要用到bind方法。 
bind的实现如下: 
复制代码 代码如下:

// The .bind method from Prototype.js 
Function.prototype.bind = function(){ 
var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift(); 
return function(){ 
return fn.apply(object, 
args.concat(Array.prototype.slice.call(arguments))); 
}; 
}; 

使用示例: 
复制代码 代码如下:
  
  var obj = { 
	name: 'A nice demo', 
	fx: function() { 
		alert(this.name); 
	} 
  }; 

  window.name = 'I am such a beautiful window!'; 

  function runFx(f) { 
	f(); 
  } 
  function fx(){
	alert(this.name);  
  }
  var fx2 = obj.fx.bind(obj); 
  runFx(obj.fx); // I am such a beautiful window!
  runFx(fx2); // A nice demo
  runFx(fx);// I am such a beautiful window!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值