loading...
Cover image for JavaScript `this` in a flash!

JavaScript `this` in a flash!

rajikaimal profile image Rajika Imal ・2 min read

this in JavaScript can be the one of the most confusing concepts to grab at first. If you want to understand this, just remember only ONE rule. Yeah, just one rule. Consider the following two scenarios below,

function person() {
    console.log(this === global)
}

person(); //true
Enter fullscreen mode Exit fullscreen mode
var person = {
    getPerson: function() {
        console.log(this === person);
    }
}

person.getPerson(); //true
Enter fullscreen mode Exit fullscreen mode

In the first snippet, the function is called directly. If that's the case, it'll always have the context (this) set as global. (In the browser it's window).

In the second snippet, the function is called from an object. In this instance this is the object itself.

Therefore the rule is: "If it's called directly without creating an object, this equals to global context, if a function is called by creating an object, then this equals to the context of the calling object".

By following this rule, other behaviors can be understood very easily. In JavaScript, there are different way to call methods. call, and apply are used to call methods by specifying objects and arguments explicitly. Both of these can change the context based on the provided object. Again apply the singular rule. The context of the method will depend on the object that is calling the method. Below snippets shows this behavior. (Note: call and apply differs with the way arguments are passed)

var person = {
    getPerson: function() {
        console.log(this.name);
    }
}

var jack = {
    name: "jack"
}

person.getPerson.call(jack); //jack, reason: even though the method is called from person object, jack object is given as the argument in call function explicitly, therefore it binds to jack object. 

person.getPerson(); //undefined, reason: person object doesn't have name in it's context
Enter fullscreen mode Exit fullscreen mode

In the below snippet, person.getPerson.call(jack); and person.getPerson(); will give two outputs.

var person = {
    name: "nancy",
    getPerson: function() {
        console.log(this.name);
    }
}

var jack = {
    name: "jack"
}

person.getPerson.call(jack); //jack

person.getPerson(); //nancy, reason: as method is called from the object and it has a name in it's context.
Enter fullscreen mode Exit fullscreen mode

When we consider all the above scenarios, it comes down to the singular rule that we established at the start.

Discussion

pic
Editor guide