thinky icon indicating copy to clipboard operation
thinky copied to clipboard

Define & ES6 arrow : this is undefined

Open tlvenn opened this issue 9 years ago • 3 comments

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;
});

tlvenn avatar Apr 21 '16 09:04 tlvenn

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/

marshall007 avatar Apr 21 '16 20:04 marshall007

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.

tlvenn avatar Apr 22 '16 01:04 tlvenn

@marshall007 -- thanks, I actually didn't know about. That was a nice read.

@tlvenn -- want to send a quick pull request on gh-pages? :)

neumino avatar Apr 22 '16 01:04 neumino