为什么不能“不”定义 Function.prototype.bind 的第一个参数并让它保留被调用的上下文是有原因的。
我有一个用例,执行此操作非常有用,但它似乎将 null 或 undefined 作为第一个参数将输出函数绑定(bind)到 Window。
换句话说,这意味着 native 绑定(bind)的当前实现似乎不允许您不绑定(bind)函数的上下文,而只将参数前缀绑定(bind)到绑定(bind)的函数。
例如:
var a = function() {
this.foo = function() { console.log(this) };
this.foo = this.foo.bind(undefined,1);
};
var b = new a();
b.foo(); // Logs Window instead of the instance b;
这已在 Google Chrome 版本 27.0.1453.116 m 中测试
最佳答案
您需要创建自己的 Binder 函数来执行此操作。使用.bind()
的主要原因是处理非词法定义的this
。因此,他们没有提供任何不设置 this
的方式来使用它。
这是一个您可以使用的简单示例:
Function.prototype.argBind = function() {
var fn = this;
var args = Array.prototype.slice.call(arguments);
return function() {
return fn.apply(this, args.concat(Array.prototype.slice.call(arguments)));
};
};
这是非常简单的,不处理作为构造函数调用的函数,但如果需要,您可以添加该支持。
您还可以将其增强为类似于原生 .bind()
的行为,除非将 null
或 undefined
作为第一个参数传递。
Function.prototype.argBind = function(thisArg) {
// If `null` or `undefined` are passed as the first argument, use `.bind()`
if (thisArg != null) {
return this.bind.apply(this, arguments);
}
var fn = this;
var args = Array.prototype.slice.call(arguments);
return function() {
return fn.apply(this, args.concat(Array.prototype.slice.call(arguments)));
};
};
关于javascript - 在没有上下文参数的情况下调用 native 绑定(bind)函数 ( Function.prototype.bind ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17354598/