js原生函数bind
来源:互联网 发布:淘宝网最新版本是多少 编辑:程序博客网 时间:2024/05/12 01:56
在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!