我想不出这个问题的简单标题。我可以用代码更好地解释它:
function Bar() {
this.string = "something";
this.event = function(e) {
console.log("This should say something: " + this.string);
}
}
var foo = new Bar();
window.addEventListener("mouseover", foo.event);
问题是“ this.string”在“ this.event”中变得不确定,因为事件侦听器将“ this”更改为引用事件。
我需要一种使它打印“东西”的方法。
任何帮助将不胜感激!
请改用箭头函数,以使内部函数不会为其获取新的上下文this
。
function Foo() {
this.string = "something";
this.event = (e) => {
console.log("This should say something: " + this.string);
}
}
var bar = new Foo();
window.addEventListener("mouseover", bar.event);
另一个选择是将this.event
函数显式绑定到实例化的对象:
function Foo() {
this.string = "something";
this.event = function(e) {
console.log("This should say something: " + this.string);
}.bind(this);
}
var bar = new Foo();
window.addEventListener("mouseover", bar.event);
您还可以在分配侦听器时将其绑定:
window.addEventListener("mouseover", bar.event.bind(bar));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句