将一个东西绑定到一个函数并像这样调用它之间是否有区别
func.bind(thing)(arg);
并通过bind
完成func.bind(thing, arg);
?我一直在做前者并且一直在努力。我相信它是一回事,但我可能是错的......
答案 0 :(得分:0)
func(arg).bind(thing);
bind
适用于func(arg)
。
func.bind(thing, arg);
在this
到func
设置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();
}())