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

有没有理由不能“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;

这是在Google Chrome版本27.0.1453.116 m中测试的

最佳答案 您需要创建自己的活页夹功能才能执行此操作.使用.bind()的主要原因是处理非词法定义的这个.因此,他们没有提供任何方法来使用它而不设置它.

这是一个你可以使用的简单例子:

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

这是相当简单的,并不处理作为构造函数调用的函数,但如果需要,您可以添加该支持.

除非将null或undefined作为第一个参数传递,否则您还可以将其增强为与原生.bind()类似的行为.

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