zl程序教程

您现在的位置是:首页 >  其他

当前栏目

jsbind函数使用闭包保存执行上下文

执行 使用 函数 保存 闭包 上下文
2023-06-13 09:14:32 时间
复制代码代码如下:

window.name="thewindowobject"
functionscopeTest(){
returnthis.name;
}
//callingthefunctioninglobalscope:
scopeTest()
//->"thewindowobject"
varfoo={
name:"thefooobject!",
otherScopeTest:function(){returnthis.name}
};
foo.otherScopeTest();//->"thefooobject!"
varfoo_otherScopeTest=foo.otherScopeTest;
foo_otherScopeTest();
//?>"thewindowobject"

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

//The.bindmethodfromPrototype.js
Function.prototype.bind=function(){
varfn=this,args=Array.prototype.slice.call(arguments),object=args.shift();
returnfunction(){
returnfn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};

使用示例:
复制代码代码如下:
varobj={
name:"Anicedemo",
fx:function(){
alert(this.name);
}
};
window.name="Iamsuchabeautifulwindow!";
functionrunFx(f){
f();
}
varfx2=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;
returnfunction(){
return_this.apply(obj,
Array.prototype.slice.call(arguments));
}
}
varname="window",
foo={
name:"fooobject",
show:function(){
returnthis.name;
}
};
console.assert(foo.show()=="fooobject",
"expectedfooobject,actualis"+foo.show());
varfoo_show=foo.show;
console.assert(foo_show()=="window",
"expectediswindow,actualis"+foo_show());
varfoo_show_bind=foo.show.bind(foo);
console.assert(foo_show_bind()=="fooobject",
"expectedisfooobject,actualis"+foo_show_bind());