为了保留上下文,该
bind方法非常有用,它是最近发布的ECMAscript5thEdition规范的一部分,此函数的实现很简单(只有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内部关键字将引用全局对象,它将警告“全局测试”。
现在,方法
fx2是该
bind方法生成的新函数,它将调用我们的函数以保留上下文并正确传递参数,它将警告“ obj test
1,2,3,4,5”,因为我们调用了该函数将其添加了两个论据,它已经 绑定 了前三个。



