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();
}

var fx2 = obj.fx.bind(obj);

runFx(obj.fx);
runFx(fx2);

参考:

http://www.prototypejs.org/api/function/bind

PS:

才发现prototypejs的API文档解释的这么详细,一定要花点时间多看看了。

我的简单的实现:

复制代码
Function.prototype.bind = function(obj) {
var _this = this;
return function() {
return _this.apply(obj,
Array.prototype.slice.call(arguments));
}
}

var name = 'window',
foo = {
name:'foo object',
show:function() {
return this.name;
}
};

console.assert(foo.show()=='foo object',
'expected foo object,actual is '+foo.show());

var foo_show = foo.show;

console.assert(foo_show()=='window',
'expected is window,actual is '+foo_show());

var foo_show_bind = foo.show.bind(foo);

console.assert(foo_show_bind()=='foo object',
'expected is foo object,actual is '+foo_show_bind());
复制代码

 

posted @   pingjiang  阅读(1775)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示