There's nothing wrong with the code you show embedded into your question - that should work just fine. The issue arises when you pass a method to .addEventListener()
as a callback (which shows in the code you have a link to).
Change this:
document.getElementById('call-func').addEventListener('click', this.fn1);
to this:
document.getElementById('call-func').addEventListener('click', this.fn1.bind(this));
The problem is that passing this.fn1
loses the value of this
so when the listener calls the callback later, the object that it belongs to is lost and then this
inside of fn1()
is wrong. In addition, .addEventListener()
explicitly sets the this
value to the DOM element that triggered the event (which is not your object).
The same thing would happen if you did this:
let f = this.fn1;
f();
Using .bind(this)
rebinds the value of this
when the listener calls it.
FYI, you could also do it this way with a fat-arrow function:
document.getElementById('call-func').addEventListener('click', () => this.fn1());
Or, an older way of doing it:
var self = this;
document.getElementById('call-func').addEventListener('click', function() {
self.fn1();
});
My preference is to use .bind(this)
.
More explanation on event listeners and this
here: "This" within es6 class method
More explanation on the general concept of how this
gets set when a function is called here: When you pass 'this' as an argument