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.