作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如果我在 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()
调用它时,调用上下文会发生变化,这就是确定 值的原因这个
。您需要使用 bind
将 this
的值锁定到 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/
我是一名优秀的程序员,十分优秀!