如果我在Javascript中有一个对象,并且其属性之一是一个函数:
function cow() {
this.timesMooed = 0;
this.sayMoo = function () {
this.timesMooed++;
return "moo";
};
}
假设我还有另一个函数,它将某些函数作为参数,调用它并记录结果:
var actionResults = [];
function doAction(action) {
actionResults.push(action());
}
现在让我们将其付诸实践,看看会发生什么:
var jerry = new cow();
doAction(jerry.sayMoo);
console.log(actionResults);
// Outputs ["moo"] -this is correct
console.log(jerry.timesMooed);
// Outputs 0 -uh oh
我如何传递函数,以便它Jerry
正在运行该函数?
当您将引用传递给函数doAction
,然后使用进行调用时action()
,调用上下文将发生变化,这就是确定的值的原因this
。您需要使用bind
来将this
locked的值保持为jerry
:
function cow() {
this.timesMooed = 0;
this.sayMoo = function () {
this.timesMooed++;
return "moo";
}
}
var actionResults = [];
function doAction(action) {
actionResults.push(action());
}
var jerry = new cow();
// use bind, which makes a function with `this` set properly
doAction(jerry.sayMoo.bind(jerry));
console.log(actionResults);
console.log(jerry.timesMooed);
或者,您可以使用按词法=>
绑定的箭头函数this
:
function cow() {
this.timesMooed = 0;
// use arrow function here instead
this.sayMoo = () => {
this.timesMooed++;
return "moo";
}
}
var actionResults = [];
function doAction(action) {
actionResults.push(action());
}
var jerry = new cow();
// no need to bind() now
doAction(jerry.sayMoo);
console.log(actionResults);
console.log(jerry.timesMooed);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句