簡體   English   中英

從實例方法中調用實例方法

[英]Call instance method from instance method

我想從method2內調用method1。 不知道如何訪問它。 我收到:

TypeError:無法調用未定義的方法“ method1”

TestSchema.methods = {
  method1: () => {
      return true;
  },
  method2: () => {
    if(this.method1()){
        console.log('It works!');
    }
  }
};

不要使用箭頭功能。 它使用函數定義的詞法范圍中的this上下文。 在您使用的strict mode ,它是未定義的。

使用常規功能:

TestSchema.methods = {
  method1: function() {
      return true;
  },
  method2: function() {
    if(this.method1()){
        console.log('It works!');
    }
  }
};

然后確保將函數作為對象的方法調用:

TestSchema.methods.method2();

您可以在此處找到有關箭頭功能的更多說明。

僅由於箭頭功能而發生此錯誤。 箭頭函數表達式本身不綁定thisargumentssupernew.target

另外,您不應該使用function關鍵字來解決此問題。 最好的解決方案是使用Shorthand method names

TestSchema.methods = {
  method1(){
    return true;
  },
  method2(){
    if (this.method1()) {
      console.log('It works!');
    }
  }
};
TestSchema.methods.method2();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM