func.bind(thing)(arg)vs func.bind(thing,arg)

时间:2014-03-25 16:11:17

标签: javascript

将一个东西绑定到一个函数并像这样调用它之间是否有区别

func.bind(thing)(arg);

并通过bind

完成
func.bind(thing, arg);

?我一直在做前者并且一直在努力。我相信它是一回事,但我可能是错的......

2 个答案:

答案 0 :(得分:0)

func(arg).bind(thing); bind适用于func(arg)

的结果

func.bind(thing, arg);thisfunc设置thing个背景。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

答案 1 :(得分:0)

假设你有一个构造函数及其对象,比如

function Arith(operand1) {
    this.operand1 = operand1;
    this.adder = function(operand2) {
        return this.operand1 + operand2;
    }
}

var arith = new Arith(5);

现在,为了演示目的,让我们创建另一个我们像这样调用的函数

invoker(arith.adder, arith);

现在,invoker函数使用您在问题中提到的两种不同方式调用函数

function invoker(func, thisArg) {
    console.log(func.bind(thisArg)(6));    // 11
    console.log(func.bind(thisArg, 6)());  // 11
    console.log(func.bind(thisArg)());     // NaN
}

因此,当您说func.bind(thisArg)时,您正在创建一个绑定到thisArg的函数,并使用6作为参数调用它。它大致相当于

(function(operand2) {
    thisArg.func(operand2);
}(6))

但是当你说func.bind(thisArg, 6)时,你正在创建一个绑定到thisArg的函数,并且你在调用时传递了第一个传递给该函数的参数。因此,您可以像Function.prototype.bind这样使用partial application of a function来完成{{3}}。它大致相当于

(function() {
    thisArg.func(6);
}())

在最后一种情况下,我们会返回NaN,因为我们没有传递operand2 adder函数的值,因此默认使用undefined代替。在JavaScript中将undefined添加到数字NaN。它大致相当于

(function() {
    thisArg.func();
}())