请考虑以下示例:
var funcToCall = function() {...}.bind(importantScope);
// some time later
var argsToUse = [...];
funcToCall.apply(someScope, argsToUse);
Run Code Online (Sandbox Code Playgroud)
我想保留funcToCall的'importantScope'.然而,我需要使用apply来应用未知数量的参数.'apply'要求我提供'someScope'.我不想更改范围,我只想将参数应用于函数并保留其范围.我该怎么办?
您可以将任何旧对象(包括null)作为第一个参数传递给apply()调用,并且this仍然可以importantScope.
function f() {
alert(this.foo);
}
var g = f.bind( { foo: "bar"} );
g(); // Alerts "bar"
g.apply(null, []); // Alerts "bar"
Run Code Online (Sandbox Code Playgroud)
该bind方法创建一个新函数,其中this值保证是您作为bind调用参数传入的对象.无论这个新函数如何调用,this都将始终如一.一个简单的实现看起来像这样(注意实现指定的ECMAScript 5和Prototype中的实现比这更多,但这应该给你的想法):
Function.prototype.bind = function(thisValue) {
var f = this;
return function() {
return f.apply(thisValue, arguments);
};
};
Run Code Online (Sandbox Code Playgroud)