It's not complicated. People simply don't take the time to learn. Which is a shame, because it takes about an hour to learn. Here are the rules in the words of Kyle Simpson:
Determining the this binding for an executing function requires finding the direct call-site of that function. Once examined, four rules can be applied to the call-site, in this order of precedence:
Called with new? Use the newly constructed object.
Called with call or apply (or bind)? Use the specified object.
Called with a context object owning the call? Use that context object.
Default: undefined in strict mode, global object otherwise.
Instead of the four standard binding rules, ES6 arrow-functions use lexical scoping for this binding, which means they adopt the this binding (whatever it is) from its enclosing function call. They are essentially a syntactic replacement of self = this in pre-ES6 coding.
Sure, some basic rules make it seem easy, but what rule is this?
button.addEventListener('click', owner.func)
3? No, but most beginners would think so, and not without reason. When it comes to callbacks the waters are murky, and that's where 99% of issues with this come from.
well, in that case the function call-site is no longer owner, but rather button. the owner object doesn't have anything to do with this function call anymore. for those cases i'd rather do something like that: button.addEventListener('click', (e) => owner.func(e)) which (probably) has the desired behaviour. or, if you don't want to use an additional function, it get's a bit messy: button.addEventListener('click', owner.func.bind(owner))
61
u/[deleted] May 28 '19
[removed] — view removed comment