如何在Loopback中创建一个可以访问自身的实例方法?

How to create an instance method in Loopback that can access itself?

在我的一个 LoopBack 模型中,我想向模型添加一个实例方法,但它不允许我访问 this,因为 this 在原型方法中未定义:

module.exports = (MyModel) => {
  MyModel.prototype.doStuff = () => {
    console.log(this);  // outputs undefined
  }
}

这显然限制了实例方法的用处。有办法吗?

问题是您正在使用 arrow function expression

An arrow function expression has a shorter syntax compared to function expressions and does not bind its own this, arguments, super, or new.target.

当您将其重写为 function(){} 时,您将可以访问模型的实例。