Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

152
Vistas
'this' keyword in array prototype function is undefined

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?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

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.

about 4 years ago · Juan Pablo Isaza Denunciar

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)};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda