let obj = {
a: 1,
getA() {
return this.a;
}
};
let getA = obj.getA;
console.log(getA());0
What is the output and why?
subina kallyani
medium
3completed
161
Answer
It prints undefined.obj.getA() is a method call, where this refers to the object obj, so this.a would be 1.
However, when we assign let getA = obj.getA; and call getA(), the function is invoked as a plain function, not as a method.
In this case, this defaults to:
In non-strict mode → the global object (window in browsers).
In strict mode → undefined.
Since this.a does not exist in the global object and this is undefined (if strict mode), the result is undefined.
Click to Reveal Answer
Tap anywhere to see the solution
Revealed
Comments0