Define & ES6 arrow : this is undefined
Hi,
It seems that we cant use ES6 function to define methods for a given model.
If we do, this is undefined.
This works
User.define("isAdult", function() {
return this.age > 18;
});
This does not
User.define("isAdult",() => {
return this.age > 18;
});
Unfortunately, this is expected behavior. Since arrow functions capture the lexical scope of the current context, this refers to the module scope in your example. In cases like these, you're forced to use a traditional function declaration, I'm afraid. This blog post explains in more detail:
http://derickbailey.com/2015/09/28/do-es6-arrow-functions-really-solve-this-in-javascript/
Hi @marshall007,
I suspected the behaviour of this with ES6 arrow was at play but I though if Thinky was aware, it could work around it but it does not seem to be the case.
I found this article particularly helpful to understand precisely how this is treated with ES6 arrow function: https://blog.getify.com/arrow-this
Thanks for your pointer as well.
The documentation should probably mention this briefly as I suspect many people don't fully understand this at first.
@marshall007 -- thanks, I actually didn't know about. That was a nice read.
@tlvenn -- want to send a quick pull request on gh-pages? :)