In my last post, we looked at the second rule in determining the value of this
inside a declared object. In my last example, the context of this
changed unexpectedly and our basketballMachine
method, the
this.lastName
became undefined because the keyword
this
referred to the
details
object.
If I told you that you can set the value of the keyword this
explicitly to be the boss
object instead of the details
object. Would you believe me? Read on.
You can set the context of this
to whatever you want using call
, apply
or bind
methods.
A thing to remember
call()
, apply()
and bind()
can only be used by functions and not any other data-types.
call()
Let's take a look at our previous example again.
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
We got undefined
here because the value of the keyword this
is bound to the details
object which does not have a lastName
property.
Let's change it to be the boss object
boss.details.basketballMachine.call(boss) //"Michael Scott the Machine"
Viola!
Note
Here, we are not invoking the basketballMachine
method, we are just attaching the call
onto it so there are no parentheses after basketballMachine
.
Top comments (0)