1

I am learning to use class in Javascript and I know how to call a variable defined in the constructor() from a method. My problem is that I am not able that same variable when the method itself is called by a listener.

I have tried to add this.value01.bind(this) unsuccessfully.

This is the code I'm using:

class mytest extends HTMLElement {
    constructor(){
    super();
    this.value01 = document.body.clientWidth;

    this.testingMethod();

    window.addEventListener( 'resize', this.onWindowResize, false)
  }

  connectedCallback(){
    console.log( "From connectedCallback()", this.value01 ); // works
  }

  testingMethod(){
    console.log( "From testingMethod()", this.value01 );
  }

  onWindowResize(){
    console.log( "From onWindowResize()", this.value01 ); // undefined!
  }
}
customElements.define("my-test", mytest);

A fiddle is available at this url: https://jsfiddle.net/1mohk8jw/2/ Resize the window and check the console to see the problem.

I would like a way the reuse a variable defined in the constructor and used in a method called by a listener. How to get rid of the undefined from the onWindowResize() method using the constant?

Student
  • 135
  • 2
  • 13

1 Answers1

0

You are seeing undefined because the binding to this is changing when the callback is invoked, it is pointing to the global object.

To solve it you need to do either of two things:

  1. Bind this explicitly to your callback so that this is always referring to your class instance.

  2. Use an arrow function syntax () => which preserves the lexical this

class Mytest{
  constructor(){
    this.value01 = document.body.clientWidth;
    window.addEventListener('click', this.thisTestWithoutBind, false);
    window.addEventListener('click', this.thisTestWithBind.bind(this), false);
    window.addEventListener('click', () => this.thisTestWithArrowFunc(), false);
  }

  thisTestWithoutBind(){
    console.log(Object.is(window, this)); //true
    console.log( "From thisTestWithoutBind()", this.value01 ); // undefined!
  }
  
  thisTestWithBind(){
    console.log( "From thisTestWithBind()", this.value01 ); // not undefined!
  }
    
  thisTestWithArrowFunc(){
    console.log( "From thisTestWithArrowFunc()", this.value01 ); // not undefined!
  }
}
new Mytest();
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44