代码之家  ›  专栏  ›  技术社区  ›  kombat

ES6:如何从回调函数调用类函数[重复]

  •  4
  • kombat  · 技术社区  · 7 年前

    我有一个类,在init方法中,我正在设置一个click事件,在该事件中,我想调用该类上的一个方法,但我不知道如何做,或者是否可能。下面的代码显示了我正在尝试的内容的结构。在classes init()函数中,在ajax返回后,我将设置一个click事件,并在该回调中调用该类的classFn()函数。我试过绑定这个,我试过self=this和binding that,箭头函数(我没想到会起作用,但我想我会试试),等等。

    class MyClass {
      constructor() {
       this.a = '';
      }
    
      init() {
        ....
        $.getJSON(url, function(data) {
          $(mySelector).click(function() {
            classFn();
          });
        });
      }
    
      classFn() {
        ....
      }
    }
    
    2 回复  |  直到 7 年前
        1
  •  9
  •   Aurel Bílý    7 年前

    function 更改的含义 this . 解决此问题的一种方法是使用 bind . 但是,您必须使用它两次,因为您有两层 作用 . 解决这个问题的一个简单方法是使用箭头函数,它不会改变 :

    class MyClass {
      constructor() {
       this.a = '';
      }
    
      init() {
        ....
        $.getJSON(url, (data) => {
          $(mySelector).click(() => {
            this.classFn();
          });
        });
      }
    
      classFn() {
        ....
      }
    }
    
        2
  •  1
  •   Shubham Khatri    7 年前

    您需要绑定回调函数并调用 this.classFn() . 你可以使用 .bind arrow function

    class MyClass {
      constructor() {
       this.a = '';
       this.init = this.init.bind(this);
      }
    
      init() {
        ....
        $.getJSON(url, function(data) {
          $(mySelector).click(function() {
            this.classFn();
          }.bind(this));
        }.bind(this));
      }
    
      classFn() {
        ....
      }
    }
    

    class MyClass {
      constructor() {
       this.a = '';
      }
    
      init = ()  => {   // class fields are stage-2 proposal with es6
        ....
        $.getJSON(url,(data) =>  {
          $(mySelector).click(()  => {
            this.classFn();
          });
        });
      }
    
      classFn() {
        ....
      }
    }