如何在javascript中绑定多个功能?

问题描述 投票:-2回答:1

在下面的代码中,我将事件侦听器附加到第二个Element上,并在单击时调用First函数,后者调用second函数。在First中,this.firstElement已定义,但是当它汇总到Second函数时,将引发错误,指出this.firstElement未定义。

  class Test{
      constructor() {
          this.firstElement = document.getElementById('firstElement');
          this.secondElement = document.getElementById('firstElement');

          this.secondElement.addEventListener("click", this.First.bind(this)); 
      }  

     First() {
         this.firstElement.append('<div> new content </div>')
         this.Second(); 
     }

     Second() {
        this.firstElement.append('<div> another content </div>' )      
     }
  } 
}
javascript
1个回答
0
投票

使用箭头函数而不是类方法来定义第一和第二。这将自动将方法绑定到此。

  class Test{
      constructor() {
          this.firstElement = document.getElementById('firstElement');
          this.secondElement = document.getElementById('firstElement');

          this.secondElement.addEventListener("click", this.First); 
      }  

     First =() =>{
         this.firstElement.append('<div> new content </div>')
         this.Second(); 
     }

     Second =() => {
        this.firstElement.append(<div> another content </div>' )      
     }
  } 

您也可以直接将函数绑定到此:

  class Test{
      constructor() {
          this.First = this.First.bind(this);
          this.Second = this.Second.bind(this);
          this.firstElement = document.getElementById('firstElement');
          this.secondElement = document.getElementById('firstElement');

          this.secondElement.addEventListener("click", this.First); 
      }  

     First() {
         this.firstElement.append('<div> new content </div>')
         this.Second(); 
     }

     Second() {
        this.firstElement.append(<div> another content </div>' )      
     }
  } 
© www.soinside.com 2019 - 2024. All rights reserved.