简体   繁体   English

javascript中如何绑定多个函数?

[英]how to bind multiple functions in javascript?

in the code below, I attach event listener to second Element and on on click it calls First function, which calls second function.在下面的代码中,我将事件侦听器附加到第二个元素,然后单击它调用第一个 function,它调用第二个 function。 in the First, the this.firstElement is defined, but when it gests to the Second function, it throws an error that this.firstElement is undefined.在第一个中,this.firstElement 被定义,但是当它到达第二个 function 时,它会抛出 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>' )      
     }
  } 
}

Define First and Second using arrow functions instead of class methods.使用箭头函数而不是 class 方法定义 First 和 Second。 This will auto bind the methods to this.这将自动将方法绑定到此。

  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>' )      
     }
  } 

You can also bind the functions to this directly instead:您也可以直接将函数绑定到 this 上:

  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>' )      
     }
  } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM