【问题标题】:Call instance method from instance method从实例方法调用实例方法
【发布时间】:2016-08-30 22:10:04
【问题描述】:

我想从方法 2 中调用方法 1。不知道如何访问它。我收到:

TypeError: 无法调用未定义的方法 'method1'

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

【问题讨论】:

  • method2 怎么称呼?
  • 测试 test = new Test(); test.method2();
  • @70656e6973 什么是Test
  • @DmitriPavlutin TestSchema 是“测试”对象的模型。

标签: javascript node.js methods mongoose


【解决方案1】:

不要使用箭头功能。它使用来自函数定义的词法范围的this 上下文。它在您使用的strict mode 中未定义。

使用常规函数:

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

然后确保将函数作为对象上的方法调用:

TestSchema.methods.method2();

你可以找到更多关于箭头函数的解释作为方法here

【讨论】:

  • 到目前为止尝试跟上 ES6。感谢您的宝贵时间
【解决方案2】:

这个错误的发生仅仅是因为箭头函数。箭头函数表达式不绑定自己的thisargumentssupernew.target

此外,您不应使用 function 关键字来解决此问题。最好的解决方案是使用Shorthand method names

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

【讨论】:

  • 感谢您提供的进一步解释+其他解决方法!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多