I’m trying to understand why the following JavaScript code logs undefined in both Node.js and browser environment instead of window/global object:
class Person {
constructor(name) {
this.name = name;
}
greet() {
function sayHello() {
console.log(this); // logs undefined in browser and node environment
}
sayHello();
}
}
const john = new Person("John");
john.greet();
I expected this
inside the sayHello() function to refer to the window
instance in browser and global
instance in node environment, but instead it logs undefined
in Node.js and browser environment. Can someone explain why this is happening ? how this
value binding to the Variable Object (VO) while the JS engine creation phase.
I know I can solve this by replacing the normal function into the arrow function to get the Person
Object, that is jhon
here.
let sayHello = () => {
console.log(this); // logs Person Object
}
sayHello();
But I want to know what happens behind the scenes of JS engine while the JS creation and execution phase. Can anyone explain this?