Lexical scope while extending prototype?
In the first case this
is window
, because it's inherited from whatever scope you call it.
For example, in this case it won't be window
:
!function() { ((n) => console.log(this))() }.call({foo: 'bar'})
In the second case this
is window
as well. But second case won't get executed, because you're running built-in String.prototype.repeat
instead. :P
Heh heh the second case was enlightening.
If I need to bind it to prototype's context, it's not possible because it's lexical, but how does one extend prototype chain with fat arrow functions?
Le 10 févr. 2014 à 09:53, Hemanth H.M <hemanth.hm at gmail.com> a écrit :
I do understand Arrow functions are like built-in functions in that both lack .prototype and any [[Construct]] internal method
It is not the main feature of arrow-functions. The essential difference between arrow- and non-arrow-function, is that the former uses a lexical this-binding and the latter uses a
this`-binding determined by call site.
When you add methods on a prototype, you typically need to have a reference to the object on which the method is called. So you need a non-arrow function.
So to finalize: There is no way to do this with fat arrow, rather fat arrow is not meant for this?
correct.
As an altrnative use a concise method:
Object.assign(String.prototype, {
repeat(n) {return Array(+n+1).join(this)}
});
Roger that!
I do understand Arrow functions are like built-in functions in that both lack .prototype and any [[Construct]] internal method.
But why does the scope refer to the global in case of :
Whereas:
Sorry if I'm missing something trivial. I did go through spec.
spec