Javascript 如何从JS类中的addEventListener集合调用变量?

Javascript 如何从JS类中的addEventListener集合调用变量?,javascript,class,Javascript,Class,我正在学习在Javascript中使用类,并且知道如何从方法调用构造函数()中定义的变量。我的问题是,当侦听器调用方法本身时,我无法使用相同的变量 我尝试添加此.value01.bind(此)失败 这是我正在使用的代码: class mytest extends HTMLElement { constructor(){ super(); this.value01 = document.body.clientWidth; this.testingMethod();

我正在学习在Javascript中使用类,并且知道如何从方法调用构造函数()中定义的变量。我的问题是,当侦听器调用方法本身时,我无法使用相同的变量

我尝试添加此.value01.bind(此)失败

这是我正在使用的代码:

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);
此url中提供了小提琴: 调整窗口大小并检查控制台以查看问题


我想要一种重用构造函数中定义的变量并在侦听器调用的方法中使用的方法。如何使用常量从onWindowResize()方法中删除未定义的?

您看到的是
未定义的
,因为调用回调时,
的绑定正在更改,它指向全局对象

要解决这个问题,您需要做两件事之一:

  • this
    显式绑定到回调,以便
    this
    始终引用类实例

  • 使用箭头函数语法
    ()=>
    ,该语法保留词法
    this

  • classmytest{
    构造函数(){
    this.value01=document.body.clientWidth;
    window.addEventListener('click',this.thisTestWithoutBind,false);
    window.addEventListener('click',this.thistTestWithBind.bind(this),false);
    window.addEventListener('click',()=>this.thistwitharrowfunc(),false);
    }
    thisTestWithoutBind(){
    console.log(Object.is(window,this));//true
    console.log(“来自thisTestWithoutBind()”,this.value01);//未定义!
    }
    thisTestWithBind(){
    console.log(“来自thisTestWithBind()”,this.value01);//未定义!
    }
    thisTestWithArrowFunc(){
    console.log(“来自thisTestWithArrowFunc()”,this.value01);//未定义!
    }
    }
    
    新Mytest()
    您看到的是
    未定义的
    ,因为调用回调时,
    的绑定正在更改,它指向全局对象

    要解决这个问题,您需要做两件事之一:

  • this
    显式绑定到回调,以便
    this
    始终引用类实例

  • 使用箭头函数语法
    ()=>
    ,该语法保留词法
    this

  • classmytest{
    构造函数(){
    this.value01=document.body.clientWidth;
    window.addEventListener('click',this.thisTestWithoutBind,false);
    window.addEventListener('click',this.thistTestWithBind.bind(this),false);
    window.addEventListener('click',()=>this.thistwitharrowfunc(),false);
    }
    thisTestWithoutBind(){
    console.log(Object.is(window,this));//true
    console.log(“来自thisTestWithoutBind()”,this.value01);//未定义!
    }
    thisTestWithBind(){
    console.log(“来自thisTestWithBind()”,this.value01);//未定义!
    }
    thisTestWithArrowFunc(){
    console.log(“来自thisTestWithArrowFunc()”,this.value01);//未定义!
    }
    }
    
    新Mytest()好的,我了解原因和解决方案。非常感谢你!好的,我明白原因和解决办法。非常感谢你!