I can't think of a straightforward title for this problem. I can explain it better with code:
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);
The problem is 'this.string' becomes undefined in 'this.event', because the event listener changes 'this' to refer to the event instead.
I need a way to get it to print "something" instead.
Any help would be highly appreciated!
Use an arrow function instead so that the inner function does not acquire a new context for its 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);
Another option would be to explicitly bind the this.event function to the instantiated object:
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);
You could also bind it when you assign the listener:
window.addEventListener("mouseover", bar.event.bind(bar));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With