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?
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
, ornew.target
.
when you rewrite it to function(){}
you'll get access to the model's instance.