'this' is for beginners II
Ajin Kabeer
Posted on April 11, 2020
This is the continuation of the series 'this' is for beginners. If you haven't read the first part yet, I highly recommend you do to get the flow of this
. Let's see what happens when the keyword this
is inside an Object declaration.
Object
This is the second rule which is object binding. This rule applies when the keyword this
is used inside a declared object. The value of the keyword this
will be closest to the value of the parent object.
Let's take a look at an example.
const boss = {
lastName:"Scott",
name: function(){
return "Michael " + this.lastName;
},
whatContext:function() {
return this;
}
}
boss.name() //Michael Scott
boss.whatContext() // returns the object boss
Now, fire-up your console and test the code snippet below. There's a catch.
const boss = {
lastName:"Scott",
whatContext:this
}
boss.whatContext // window object
But why?
The keyword this
is defined when a function is run. As simple as that. There is not a function being run here to create a new value of the keyword this
so the value of this
is still the window object.
Nested Objects
Let's look at a bit more complex object with nested properties.
const boss = {
lastName:"Scott",
name: function(){
return "Michael " + this.lastName;
},
whatContext:function() {
return this;
},
details: {
basketballMachine: function(){
return "Michael " + this.lastName + " the Machine";
},
whatContext:function(){
return this
}
}
}
boss.details.basketballMachine() //Michael undefined the Machine
Inside of the details
object, we have a key of basketballMachine
which is a function that returns the string "Michael" concatenated with the value of the lastName
property.
The second rule is that the value of the keyword this
will always be the closest parent object. Even though, the declared object is boss
, there's an object inside called details
which is the closest parent object to the basketballMachine
object.
Since the details
object does not have a key of lastName
the value of this.lastName
will be undefined
.
So how can we fix this?
What if we want our basketballMachine
method to return Michael Scott the Machine instead of Michael undefined the Machine.
That is exactly the call()
, apply()
and bind()
functions will do for us.
In the next part, we will look at the third rule for determining the value of this
using call()
, apply()
and bind()
.
So Long..
Posted on April 11, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.