在没有上下文参数的情况下调用本机绑定函数(function.prototype.bind)

Calling native bind function ( Function.prototype.bind ) without a context argument

本文关键字:函数 绑定 function prototype bind 本机 调用 上下文 参数 情况下      更新时间:2023-09-26

我们为什么不能"not"定义Function.prototype.bind的第一个参数,并让它保留被调用的上下文。

我有一个用例,它非常有用,但它似乎传递null或undefined作为第一个参数,将输出函数绑定到Window。

另一种说法是,本机绑定的当前实现似乎不允许您不绑定函数的上下文,而只将参数前缀绑定到绑定的函数。

例如:

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;

这是在谷歌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(),除非将nullundefined作为第一个参数传递。

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)));
    };
};