[英]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();
您可以在此處找到有關箭頭功能的更多說明。
僅由於箭頭功能而發生此錯誤。 箭頭函數表達式本身不綁定this
, arguments
, super
和new.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.