4

I have a prototype function written on the Array class like

Array.prototype.myfunc = () => 
{
   // ... 
}

and within the body this is referring to window when I call it on an array like

var result = [1, 69, -1, 1].myfunc();

How can I make it refer to the array on which it's being invoked?

user6048670
  • 2,669
  • 3
  • 12
  • 18
  • Why do you use lambdas BTW? They're still not supported by many browsers. – Bálint Jul 11 '16 at 00:47
  • 1
    Related: [Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?](http://stackoverflow.com/q/34361379/218196) – Felix Kling Jul 11 '16 at 03:32

4 Answers4

5

The () => { } arrow syntax binds to the current this which likely is window (depending on when you assign the function).

Daniel A. White
  • 174,715
  • 42
  • 343
  • 413
2

The fat arrow syntax in ES6 is an implicit bind to the current scope.

If your current scope is Window (or the global scope), then the function you just set on the prototype is bound to that scope.

You still need the good ol' function () syntax for behavior without binding.

drkibitz
  • 467
  • 5
  • 14
1

Just don't use arrow function here, arrow function inherits context from the parent scope.

Array.prototype.myfunc = function() {
   // ... 
}
Max Brodin
  • 3,712
  • 1
  • 11
  • 21
0

What's causing your issue is the use of an arrow function.

In arrow functions, the this keyword may reference to:

  1. window (if accessed globally, not in strict mode),
  2. undefined (if accessed globally, in strict mode),
  3. an instance (if in a constructor),
  4. an object (if in a method or function inside an object or instance) or
  5. a binded/applied value.

To fix your issue, you have to use a "normal" function() and you can call your function using call(this, ...params):

  • In this you put the object you want the keyword this to be bound to and
  • In ..args you put your function's parameters if any.

So, with the above in mind, your code can be as shown:

Array.prototype.myfunc = function(...) {
   // Your code
}

var array = [1, 69, -1, 1];
var result = myfunc.call(array, ...);
  • Using array as the first argument in call(), you bind the this keyword to array.
Angel Politis
  • 9,949
  • 12
  • 43
  • 62