如何将函数绑定为对象的 属性
How to bind function as a property of object
我有一个接受对象 属性 的函数,在这个对象中我想将一个函数作为属性之一传递。我想在调用 属性 时执行该函数。我需要绑定函数,因为在执行函数之前 this 上下文丢失了。
var myfunction = function () {
console.log("Something");
}
// this works
this.HeaderService.setState({
leftButton: {
click: this.myfunction.bind(this)
}
});
// can't get this to work
const self = this;
this.HeaderService.setState({
leftButton: {
click() {
return (function () {
console.log("something");
}).bind(this)
}
}
})
我可以让函数表达式起作用,但我无法得到第二种情况,我想将函数定义为 属性 单击的值。我该怎么做?
继续@JamieTorres 建议的箭头函数解决问题
const self = this;
this.HeaderService.setState({
leftButton: {
click: () => {
return (function () {
console.log("something");
}).bind(this)
}
}
})
我有一个接受对象 属性 的函数,在这个对象中我想将一个函数作为属性之一传递。我想在调用 属性 时执行该函数。我需要绑定函数,因为在执行函数之前 this 上下文丢失了。
var myfunction = function () {
console.log("Something");
}
// this works
this.HeaderService.setState({
leftButton: {
click: this.myfunction.bind(this)
}
});
// can't get this to work
const self = this;
this.HeaderService.setState({
leftButton: {
click() {
return (function () {
console.log("something");
}).bind(this)
}
}
})
我可以让函数表达式起作用,但我无法得到第二种情况,我想将函数定义为 属性 单击的值。我该怎么做?
继续@JamieTorres 建议的箭头函数解决问题
const self = this;
this.HeaderService.setState({
leftButton: {
click: () => {
return (function () {
console.log("something");
}).bind(this)
}
}
})