如何在JavaScript上访问“this”的父级?

时间:2017-05-07 15:34:12

标签: javascript class oop this

我在Javascript中编写面向对象的问题。我有以下内容:

class Foo{
    constructor(){...}
    ...
    a_needed_method(){...}
    ...
    a_method(){
        ...
        jsObject.on("click",function(params){
            this.a_needed_method();
        });
    }  
}

问题是,如果我使用a_needed_method调用this方法,那么this将引用控制onclick事件的匿名函数。我如何从这个匿名函数中调用a_needed_method()

3 个答案:

答案 0 :(得分:4)

ES6

您可以使用箭头功能来保留词汇

jsObject.on("click", params => {
  this.a_needed_method();
});

ES5

您可以使用优质的that = this

var that = this;
jsObject.on("click", function (params) {
  that.a_needed_method();
});

答案 1 :(得分:1)

您可以使用bind

    jsObject.on("click",function(params){
        this.a_needed_method();
    }.bind(this));



let jsObject = $(this);

class Foo {
  constructor() {

  }

  a_needed_method() {
    console.log('That works !');
  }

  a_method() {
    jsObject.on("click", function(params) {
      this.a_needed_method();
    }.bind(this));
  }
}

let x = new Foo();
x.a_method();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click anywhere
&#13;
&#13;
&#13;

来自arrow

es6函数:

    jsObject.on("click",(params) => {
        this.a_needed_method();
    });

&#13;
&#13;
let jsObject = $(this);

class Foo {
  constructor() {

  }

  a_needed_method() {
    console.log('That works !');
  }

  a_method() {
    jsObject.on("click", (params) => {
      this.a_needed_method();
    });
  }
}

let x = new Foo();
x.a_method();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click anywhere
&#13;
&#13;
&#13;

答案 2 :(得分:1)

在构造函数中,您可以说:

constructor(){
  this.a_needed_method = this.a_needed_method.bind(this);
}