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

180
Visualizações
"this" keyword does not refer to global object in my javascript program

I implemented this code by using javascript to check how this works in arrow function.

variable = 'Global variable';

function normalFunc () {
  console.log(this.variable);
}

const arrowFunc = () => {
  console.log(this.variable);
};

const objNormal = {
  variable: 'Inner variable',
  func: normalFunc
};

const objArrow = {
  variable: 'Inner variable',
  func: arrowFunc
};

objNormal.func();
objArrow.func();

arrowFunc();

I learned that this refers to global object in arrow function, so i expected the output like this👇

Inner variable
Global variable
Global variable

BUT the actual output was this...👇

Inner variable
undefined
undefined

Actually, it's really strange because this depends on where to run this code... in JS Fiddle, this refer to global object as i expected. But in my terminal and this playground site, this does not refer to global object.

Am i misunderstanding about this or just something is missing in my code?

Please help me to understand why this happens.

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The website linked transpiles the JS code to be inside a function, so this is not window. If you change your first line to be

this.variable = 'Global variable';

the code works as expected.

When this is pasted into a .js file (filename.js) and ran with node (node filename.js), the this keyword is an empty object while global is a completely different thing. This is different from running this code in the REPL mode, where this === global.

In both cases, when you just say variable = 'Global variable';, you're assigning to window.variable or global.variable, so you can't access it with this.variable.

about 4 years ago · Santiago Trujillo 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