为了保留上下文,bind
方法确实有用,它现在是最近发布的一部分ECMAScript 第五版 http://www.ecma-international.org/publications/standards/Ecma-262.htm规范来说,这个函数的实现很简单(只有8行长):
// The .bind method from Prototype.js
if (!Function.prototype.bind) { // check if native implementation available
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)));
};
};
}
你可以在你的例子中使用它,如下所示:
MyClass.prototype.myfunc = function() {
this.element.click((function() {
// ...
}).bind(this));
};
另一个例子:
var obj = {
test: 'obj test',
fx: function() {
alert(this.test + '\n' + Array.prototype.slice.call(arguments).join());
}
};
var test = "Global test";
var fx1 = obj.fx;
var fx2 = obj.fx.bind(obj, 1, 2, 3);
fx1(1,2);
fx2(4, 5);
在第二个例子中,我们可以更多地观察到bind
.
它基本上生成一个新函数,它将负责调用我们的函数,保留函数上下文(this
值),定义为第一个参数bind
.
其余的参数只是传递给我们的函数。
请注意,在此示例中,该函数fx1
, 被调用时没有任何对象上下文 (obj.method()
),就像一个简单的函数调用一样,在这种类型的调用中,this
里面的关键字将引用 Global 对象,它会提醒“global test”。
现在fx2
是新函数bind
生成的方法,它将调用我们的函数,保留上下文并正确传递参数,它会警告“obj test 1, 2, 3, 4, 5”,因为我们调用它添加了两个附加参数,它已经有了binded前三个。