js bind 函数 使用闭包保存执行上下文
2011-12-26 00:00
1301 查看
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());
相关文章推荐
- js bind 函数 使用闭包保存执行上下文
- Js bind 函数 使用闭包保存执行上下文
- bind 函数 - 使用闭包保存执行上下文
- js bind()函数 使用闭包保存执行上下文
- JS闭包、自执行函数小记
- js笔记---作用域(执行上下文[execution context],活动对象) 闭包
- JS——坑2(函数不调用不执行,闭包)
- C# winForm中直接使用网站JS函数的快捷方法,可执行多种JS函数
- js 中闭包和立即执行函数
- js立即执行函数的使用
- JS ES6中setTimeout函数的执行上下文示例
- JS中使用apply、bind实现为函数或者类传入动态个数的参数
- js中当函数执行bind后再次执行bind或call时会怎样
- 使用回调函数,来确定js函数执行顺序
- js笔记---作用域(执行上下文[execution context],活动对象) 闭包
- js使用闭包时,内部函数是直接访问外部函数的实际变量而非复制一份新变量
- 在立即执行函数内组合使用构造函数模式和原型模式创建对象,实现模块化开发(以daterangepicker.js为例)
- 采用自执行的匿名函数解决for循环使用闭包的问题
- JS运行过程,作用域和上下文的作用,自执行函数