0

I would like to write my own function for every array and I'm using the prototype keyword.

The problem is that when I created the following script:

Array.prototype.test = () => {console.log('length: ',this.length)};

const result = [1,2,3].test();

If I run it in the console of chrome I get the following result:

length:  0

If I run it on my local machine with node script.js I get the following result:

length:  undefined

Why is this.length different and why it doesn't reflect the length of the array I'm calling the function on?

ste
  • 3,087
  • 5
  • 38
  • 73

2 Answers2

0

That's because you are using the arrow function syntax. The arrow function does not possess a this context, so it "points" to the global context.

The solution is simple:

Array.prototype.test = function() {console.log('length: ', this.length)};

const result = [1,2,3].test(); // length:  3

By adding explicitly function now your context (this) points to the object calling the function.

JuanDeLasNieves
  • 354
  • 1
  • 3
  • 8
0

You are using an arrow function syntax.

When the "this" keyword are being called, it falls back into the global object.

In the browser it falls back into the window object and for this reason it's return 0 length.

But in the global node object, the length is undefined.

Instead, use the function keyword to get the Array.prototype context.

Array.prototype.test = function(){console.log('length: ',this.length)};
Yedidya Rashi
  • 1,012
  • 8
  • 18