const obj = {
name: "John",
outer() {
function inner() {
console.log(this.name);
}
inner();
}
};
obj.outer();0
What will be the output of the following JavaScript code and why?
kallyani
medium
0completed
6
Answer
The output will be:
undefined- The method
outer()is called usingobj.outer(), so insideouter,thisrefers toobj. - However,
inner()is a regular function, not a method of the object. - When
inner()is called, it is executed without any object reference. - In JavaScript, for a normal function call,
thisrefers to the global object (orundefinedin strict mode). - Since the global object does not have a
nameproperty,this.namebecomesundefined.
Click to Reveal Answer
Tap anywhere to see the solution
Revealed
Comments0