Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
"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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!