DEV Community

Ajin Kabeer
Ajin Kabeer

Posted on

3 2

'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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay