[英]How to bind function as a property of object
我有一个带有对象属性的函数,在这个对象中我想将一个函数作为属性之一传递。 我想在调用该属性时执行该函数。 我需要绑定该函数,因为在执行该函数之前会丢失此上下文。
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)
}
}
})
我可以使函数表达式起作用,但是我无法获得第二种情况,即我想将函数定义为属性click的值。 我该怎么做呢?
继续@JamieTorres建议的箭头功能可解决此问题
const self = this;
this.HeaderService.setState({
leftButton: {
click: () => {
return (function () {
console.log("something");
}).bind(this)
}
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.