DEV Community

Cover image for This Keyword in Javascript
Faisal Ahmed
Faisal Ahmed

Posted on • Updated on

This Keyword in Javascript

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;
    }

};
Enter fullscreen mode Exit fullscreen mode

Run getDetails function: console.log(statement.getDetails())
output:

lets see  MERN  normal function awesome.
Enter fullscreen mode Exit fullscreen mode

again run getDetails2 function : console.log(statement.getDetails2())
output:

let us see  arrow function  arrow function awesome.
Enter fullscreen mode Exit fullscreen mode

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;
            } 
        };
    }

};
Enter fullscreen mode Exit fullscreen mode

again run getDetails3() function : statement.getDetails2().getDetails3()
output:

lets see Node  React awesome.
Enter fullscreen mode Exit fullscreen mode

Advance2


Enter fullscreen mode Exit fullscreen mode

again run getDetails3() function : statement.getDetails2().getDetails3()
output:


Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
lq profile image
LiQiang

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'.

Collapse
 
webfaisalbd profile image
Faisal Ahmed

Yes.

Collapse
 
lq profile image
LiQiang

The problem is very strange.

Collapse
 
webfaisalbd profile image
Faisal Ahmed

I think that is one of the reason to come in arrow function in javascript.