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

318
Visualizações
Why is JavaScript producing "this" output?

I have been using JavaScript for some time now, but this particular piece of code has perplexed me a bit.

Why is this the output of the following piece of code

length = 10;
function func() {
  console.log(this.length);
}

var obj = {
  length: 5,
  thisFunc: function(func) {
    func();
    arguments[0]();
  }
};

obj.thisFunc(func, 3);

producing

10
2

and not

10
5

or at least

10
10

Could somebody explain to me where the value 2 is coming from and what I missed when it comes to this in this(no pun intended) particular instance?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In the first case, it is same as doing console.log(this.length) anywhere in the global scope. So it will be 10 as you understand.

As mentioned in the comments, arguments object is an array-like object which has a property length.

You can use arguments.length to count how many arguments the function was called with`

In the above quote, the called with part is important.

In the second case, the function is run in the context of the arguments object. You know that the value of this inside a function depends on how it is invoked. Here this is the arguments object, whose length is 2.

length = 10;
function func() {
  console.log(this.length);
}

var obj = {
  length: 5,
  thisFunc: function(func) {
    
    func();
    arguments[0]();
    console.log(arguments.length);
  }
};

obj.thisFunc(func, 3);
console.log(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