Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Avoid 'this' in object constructor getting overwritten by event?

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!

like image 510
MysteryPancake Avatar asked May 08 '26 04:05

MysteryPancake


1 Answers

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));
like image 86
CertainPerformance Avatar answered May 09 '26 18:05

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!