The code below creates a listener for an onchange
event in a html element inside a web component. It uses an arrow function. Inside this function, I used the this
keyword to refer to the component object (of type EulInstance
).
class EulInstance extends HTMLElement {
constructor() {
super();
this.value = "Hi!";
}
...
async render() {
...
document.getElementById(selectId).onchange = evt => {
console.log("this:", this);
console.log("this.value:", this.value);
};
}
}
But this
points to another object. In the console, I get:
this:
+ <eul-instance edit="true" language="pt" types="["http://dbpedia.org/ontology/Provider" ..."
...
</div></eul-instance>
this.value: undefined
To which object is this
pointing? It has the html text of the EulInstance
web component but not its fields.
The this
keyword behavior in the new ECMAScript 6 arrow functions is different from older anonymous functions (using function(x) {...}
). My question is different from How to access the correct this
inside a callback?. This older question says that "ECMAScript 6 introduces arrow functions, which can be thought of as lambda functions. They don't have their own this binding. Instead, this is looked up in scope just like a normal variable.". That being correct, the variable that
and this
, in the code bellow, should both point to an EulInstance object, but this
doesn't.
...
async render() {
...
const that = this;
document.getElementById(selectId).onchange = evt => {
console.log("this:", this);
console.log("this.value:", this.value);
console.log(that === this); // Had to be true
};
}