0

I'm trying to make a simple website where you can create different pages with content. To accomplish this, i thought it would be clean to have a object represent a page:

class Subpage {
  constructor(content) {
    this.content = content;
  }

  handleEvent(event) {
    document.getElementById('container').innerHTML = this.content;
  }
}
page = new Subpage("test");
document.getElementById('btn').addEventListener('click', page.handleEvent);

The page has a <div> with id container, and a button with id btn. However, instead of setting container's content to page.content, clicking btn sets it to undefined. Further investigation reveals that in handleEvent, this refers not to the object but to btn. This bizarre behaviour makes me question: what is the usefulness of having an object handle events if they can't even refer to themselves? I am aware there are other questions about this, but their answers seem hacky and not very clean, and the question remains of why is the behaviour like this, and what is the right way to code this.

  • 2
    Because with traditional functions (`function` keyword) and class methods (like your `handleEvent`), `this` is set by *how the function is called*, not where it's defined. (This -- no pun -- is different in JavaScript than some other languages.) See [this question](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) for the general way `this` works (or my blog post [here](http://blog.niftysnippets.org/2008/04/you-must-remember-this.html)), and [this question](https://stackoverflow.com/questions/20279484/) for how to ensure the correct `this` in your callback. – T.J. Crowder Mar 30 '21 at 15:45
  • In short, in this case you could get away with adding the following to your constructor: `this.handleEvent = this.handleEvent.bind( this );` – Alain Doe Mar 30 '21 at 15:49
  • 1
    https://stackoverflow.com/questions/41385835/invocation-context-and-execution-context-in-javascript-are-we-talking-of-th/41386097#41386097 (see the invocation context part). – Scott Marcus Mar 30 '21 at 15:55

0 Answers0