DEV Community

Cover image for 'this' is for beginners II
Ajin Kabeer
Ajin Kabeer

Posted on

'this' is for beginners II

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

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

Alt Text

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

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

Top comments (0)