-1

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="[&quot;http://dbpedia.org/ontology/Provider&quot; ..."
...
</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
        };
   }
dilvan
  • 2,109
  • 2
  • 20
  • 32

1 Answers1

0

Arrow functions take the context (aka this) from their parent, so this inside the arrow function will be the same as the this inside the render() function. However that doesn't necessarily have to be an EulInstance:

 const fn = (new EulInstance()).render;
 fn(); // calls render with "this" being undefined

So you should check how you call render() ...

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • The `render` function is called by the `connectedCallback` method: Invoked each time the custom element is appended into a document-connected element. This will happen each time the node is moved and may happen before the element's contents have been fully parsed. To which object is `this` pointing? Any idea? – dilvan Feb 25 '19 at 12:54