将值绑定到 javascript 中的函数
Binding a value to a function in javascript
假设我有这个功能:
function toy(input) {
return input + 1;
}
我想生成一个函数,通过将 3 绑定到输入来打印 4。这样我就可以调用 fn() 之类的东西,它会打印 4.
所以我尝试这样做:
var fn = toy.bind(3);
然后当我执行 fn() 时,我没有得到 4。
我需要使用 'this' 才能使这个 work/Is 有没有绑定的方法吗?
bind
的第一个参数是 this
的上下文,因此您需要将 3 作为第二个参数传递:
var fn = toy.bind(this, 3);
然后就可以了:)
传递给 .bind()
的第一个参数用作被调用函数中的 this
。传递给被调用函数的第一个参数是传递给 .bind()
的 第二个 参数。您 可以 使用有意义的 this
绑定(如果有的话),或者如果函数忽略 this
:
则只使用 null
var fn = toy.bind(null, 3);
Is there a way to do this without bind
?
是:
var fn = function() { return toy(3); };
或者,如果您想传递 fn
的 this
:
var fn = function() { return toy.call(this, 3); };
假设我有这个功能:
function toy(input) {
return input + 1;
}
我想生成一个函数,通过将 3 绑定到输入来打印 4。这样我就可以调用 fn() 之类的东西,它会打印 4.
所以我尝试这样做:
var fn = toy.bind(3);
然后当我执行 fn() 时,我没有得到 4。
我需要使用 'this' 才能使这个 work/Is 有没有绑定的方法吗?
bind
的第一个参数是 this
的上下文,因此您需要将 3 作为第二个参数传递:
var fn = toy.bind(this, 3);
然后就可以了:)
传递给 .bind()
的第一个参数用作被调用函数中的 this
。传递给被调用函数的第一个参数是传递给 .bind()
的 第二个 参数。您 可以 使用有意义的 this
绑定(如果有的话),或者如果函数忽略 this
:
null
var fn = toy.bind(null, 3);
Is there a way to do this without
bind
?
是:
var fn = function() { return toy(3); };
或者,如果您想传递 fn
的 this
:
var fn = function() { return toy.call(this, 3); };