In javascript, this means immediate parent context.
- But when you use this keyword in arrow function, then it does not mean in immediate parent context. It means self context.
*Just see the two code output and think the difference between them *
var title = " awesome.";
var statement = {
name: ' MERN ',
lang: 'Javascript',
getDetails: function () {
name = "normal function";
return "lets see " + this.name+ " " + name + title;
},
getDetails2: () => {
name = " arrow function";
return "let us see " + this.name + " " + name + title;
}
};
Run getDetails function: console.log(statement.getDetails())
output:
lets see MERN normal function awesome.
again run getDetails2 function : console.log(statement.getDetails2())
output:
let us see arrow function arrow function awesome.
here, output is: arrow function arrow function twice. so we understand that our this.name keyword does not mean parent name: ' MERN '.
Advance
var title = " awesome.";
var statement = {
name: ' MERN ',
lang: 'Javascript',
getDetails: function () {
name = "normal function";
return "lets see " + this.name+ " " + name + title;
},
getDetails2: () => {
name = " React";
return {
name: "Node",
getDetails3: function() {
return "lets see " + this.name+ " " + name + title;
}
};
}
};
again run getDetails3() function : statement.getDetails2().getDetails3()
output:
lets see Node React awesome.
Advance2
again run getDetails3() function : statement.getDetails2().getDetails3()
output:
Top comments (4)
I see.
ES2015 introduced arrow functions which don't provide their own this binding (it retains the this value of the enclosing lexical context).
So, in getDetails2(), 'this.name' is the same as 'name'.
Yes.
The problem is very strange.
I think that is one of the reason to come in arrow function in javascript.