Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 'this' equal to 'Window' in my prototype function? [duplicate]

Tags:

javascript

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?

like image 751
user6048670 Avatar asked Feb 07 '23 14:02

user6048670


2 Answers

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

like image 58
Daniel A. White Avatar answered Feb 11 '23 00:02

Daniel A. White


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.

like image 39
drkibitz Avatar answered Feb 11 '23 00:02

drkibitz