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

341
Visualizações
What is the lexical environment inside a callback function?

I keep hearing that arrow functions inherit the value of this from their Lexical Environment.

Consider this example:

let para = document.getElementById("para");
let article = document.getElementById("article");

article.addEventListener("click", () => {
  console.log("I’m a <span> tag!", this);
  event.stopImmediatePropagation();
});
para.addEventListener("click", () => console.log("I’m a <p> tag!", this));
<p id="para">
  <span id="article">Click Me!</span>
</p>

Why is the value of this inside the arrow callback functions undefined (or in non-strict mode: window)? If the callback function is using the value of this from its lexical environment, shouldn’t the lexical environment be addEventListener?

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

0

I think you should check out the Arrow Function on MDN they fully explained what the arrow function is and compared the traditional function to the arrow function.

According to MDN:

Arrow function does not have its own bindings to this or super, and should not be used as methods.

Therefore, in your case, the arrow function is not gonna redefined this that means this is window object

And the traditional function is redefined this from what a function is called.

para.addEventListener("click", function () {
    console.log(this);  // print p node elemnt
});
about 4 years ago · Juan Pablo Isaza Relatório

0

When you call a function as func(a, b), then first, a is evaluated, then b is evaluated, then func is called with the values of a and b. a and b are not “inside” func.

It doesn’t matter which of the following code snippets you use — these are equivalent:

const a = () => console.log(this);

addEventListener("click", a);
addEventListener("click", () => console.log(this));

addEventListener does attempt to call its second argument with this set to the event’s currentTarget, but as explained in the documentation and various other Q&A, arrow functions cannot be rebound:

"use strict";

(() => console.log(this)).call({ "my": "object" }); // Logs `undefined`.

I’m not quite sure what you mean by “shouldn’t the lexical enironment be addEventListener?”. The lexical scope of an arrow function is the one it’s created in. As an arrow function is created, its scope and a special “lexical-this” flag are used to create a function object. And when called, note that the attempt to perform the OrdinaryCallBindThis abstract operation, which normally sets this, does nothing for arrow functions. Instead, the function body is executed as-is, in its original context.

Looking at your original code again, note that every single this is part of the same lexical environment — in fact, this is the same, in this code, no matter where you put it. Note, in particular, that function arguments don’t create a new lexical environment.

"use strict";

this; // `undefined`.

let para = document.getElementById("para", this); // Ignored argument, but is `undefined`.
let article = document.getElementById("article");

article.addEventListener("click", () => {
  console.log(this); // Logs `undefined`.
  event.stopImmediatePropagation();
});
para.addEventListener("click", (this, () => console.log(this))); // Logs `undefined`. Preceded by comma operator with discarded value `this`, but would be `undefined`.

In contrast, a function function would create a new lexical environment and would also be able to be rebound:

article.addEventListener("click", function(){
  console.log(this); // Logs `article`.
});

See How does the “this” keyword work? for a more detailed explanation.

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