Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
'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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda