Lexical scope while extending prototype?

# Hemanth H.M (11 years ago)

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 :

String.prototype.repeat = (n) => Array(+n+1).join(this);

"ES6 ".repeat(3);

// will result in "[object Window][object Window][object Window]"

Whereas:

String.repeat = (n) => Array(+n+1).join(this);

"ES6 ".repeat(3) // Works fine resulting in "ES6 ES6 ES6"

Sorry if I'm missing something trivial. I did go through spec.

spec

# Alex Kocharin (11 years ago)

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

# Hemanth H.M (11 years ago)

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?

# Claude Pache (11 years ago)

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 athis`-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.

# Hemanth H.M (11 years ago)

So to finalize: There is no way to do this with fat arrow, rather fat arrow is not meant for this?

# Allen Wirfs-Brock (11 years ago)

correct.

As an altrnative use a concise method:

Object.assign(String.prototype, {
    repeat(n) {return Array(+n+1).join(this)}
});
# Hemanth H.M (11 years ago)

Roger that!