Search code examples
methodsinstanceloopbackjsstrongloop

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


In one of my LoopBack models I want to add an instance method to a model, but it won't let me access the this, as this is undefined inside the prototype method:

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

This obviously limits the usefulness of a instance method. Is there a way to do this?


Solution

  • The problem is that you're using 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.

    when you rewrite it to function(){} you'll get access to the model's instance.