I figured this doubt out while typing the question, but I think it still makes sense to have this documented for future devs.
Looking for help with understanding outputs of following: (primarily case 4 vs case 5)
var obj1 = {
x:1,
getX: function () {
const inner = () => {
console.log('1:',this.x);
}
inner();
}
}
obj1.getX();
var obj2 = {
x:1,
getX() {
const inner = () => {
console.log('2:',this.x);
}
inner();
}
}
obj2.getX();
var obj3 = {
x:1,
getX: () => {
const inner = () => {
console.log('3:',this.x);
}
inner();
}
}
obj3.getX();
function a() {
this.x = 1;
function b() {
console.log('4: ', this.x);
}
b();
}
a();
var obj5 = {
x: 1,
getX() {
const inner = function() {
console.log('5: ',this.x);
}
inner();
}
}
obj5.getX();
SPOILER ALERT!!! BELOW THIS LINE ARE MY GUESSES AND EXPLANATIONS!!! Best to try these out on your own before reading further.
My understandings:
Case 1: Since inner is an arrow function, this of parent is considered. Hence 1
makes sense.
Case 2: Semantically, I don't see any difference between Case 1 and Case 2. Please correct me if I am wrong here.
That is, {getX(){}}
vs {getX: function(){}}
should be equivalent.
Case 3: Since both inner and getX are arrow functions, this
represents that of window scope and hence accordingly the output should be undefined
.
Case 4: Since call to inner function does not have object associated, it's this refers to parent method's this
which implies same as that of a
. Hence, output is 1.
Case 5: Since call to inner function does not have object associated, it's this refers to parent method's this
which implies same as obj4
obj5
. Hence output should be 1.
NOTE: Case 5 output is undefined
. Need help understanding this.
NOTE 2: In console of new browser tab, copy paste only Case 5. You will see undefined
. While if you copy paste all of these cases together, output for Case 5 will be 1.