gpt4 book ai didi

javascript - 如何将作为另一个对象的属性的函数传递给函数并在 javascript 中调用它?

转载 作者:行者123 更新时间:2023-11-30 08:22:34 25 4
gpt4 key购买 nike

如果我在 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() 调用它时,调用上下文会发生变化,这就是确定 值的原因这个。您需要使用 bindthis 的值锁定到 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);

或者,您可以使用箭头函数 =>,它在词法上绑定(bind) 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);

关于javascript - 如何将作为另一个对象的属性的函数传递给函数并在 javascript 中调用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51128426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com