'this' is for beginners III

ajinkabeer

Ajin Kabeer

Posted on April 12, 2020

'this' is for beginners III

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 basketballMachinemethod, thethis.lastNamebecame undefined because the keywordthisreferred to thedetails 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
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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.

πŸ’– πŸ’ͺ πŸ™… 🚩
ajinkabeer
Ajin Kabeer

Posted on April 12, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related