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?