JavaScript `this` in a flash!
Rajika Imal
Posted on September 1, 2020
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
var person = {
getPerson: function() {
console.log(this === person);
}
}
person.getPerson(); //true
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
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.
When we consider all the above scenarios, it comes down to the singular rule that we established at the start.
Posted on September 1, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.