DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Harendra Bhujel
Harendra Bhujel

Posted on

4 Rule of `this` in JavaScript

One article seems to be too short to cover the awesomeness of this so we will discuss this in two-part series.

As confusing as this in JavaScript can be, it is an important concept in JavaScript that every JS developer should know.
this provides the foundation for Object-Oriented in JavaScript.
I am not a pro but I will try my best to explain what I have understood about this.

Objective

  • Define what the keyword this in JavaScript
  • Understand the four rules to figure out the value of this

So what is this?

this is a reserved keyword in JavaScript which simply refers to the object it currently belongs to. The value of this is set on the execution context, usually determined by how a function is called so the value of this change during execution.

Four Rules of this

The value of this can be determined using one of the following rules.
(These are not an official rule, just something I learned from awesome developers our there)

  1. Global Context Rule
  2. Object or Implicit Rule
  3. Explicit Rule (call, bind and apply)
  4. new Rule (new keyword in JavaScript)

1. Global Context Rule

Reminder: this points to the object it currently belongs to.

When this is not inside any declared object, then this points to the window objec.
Every variable declared in the global scope is attached to the window object.

Basically ,in browser,

let name = 'blank';

is same as

window.name = 'blank';

Let's look at the value of this in our browser.

console.log(this); // Window{...}, window object

Here this points to the window object because this is inside the window object.

We can verify if this is really pointing to the window object.

this === window; // true

As we can see, this is equal to the window object.

Now let's look at the value of this inside a function.

function whatIsThis() {
    return this;
}

whatIsThis(); // Window { ... }, Window Object

Even though we have called this inside a function, this is still inside the window object so it still points to the window object.

Let's look at another example.

function variableInThis() {
   this.person = 'blank';
}

// calling our function

variableInThis();

// let's check the value of `person` variable
console.log(person); // 'blank'
console.log(Window.person); // 'blank'

All in all, this points to the window object because this belongs to the window object and any variable we globally create is a property attached to the window object.

2. Object or Implicit Rule

Reminder: this points to the object it currently belongs to.
Or we can also say it points to it's closest object.

When we declare an object implicitly, then this inside that object points to that object, and not the window object.

let person = {
   firstName: 'blank',
   sayHi: function() {
      return `Hi ${this.firstName}!`;
   },
   determineContext: function() {
      return this === person;
   },
   whatIsThis: function() {
      return this;
   }

};
person.sayHi() // 'Hi blank'

Here we implicitly declare an object, so this inside the person object points to the person object itself and not the window object.

Meaning, inside the person object, doing

...
   return `Hi ${this.firstName}`;
...

is same as doing

...
   return `Hi ${person.firstName}`;
...

Let's see the value of this inside the person object

whatIsThis() // {firstName: "blank" ... }
person.determineContext(); // true

We can see that person === this is true so we can confidently say that this is pointing to the person object. (and not the window object.)

Now let's look at a nested object and find the value of this inside the inner object.
Reminder Again: this points to the object it currently belongs to.

var person = {
   firstName: 'blank',
   sayHi: function() {
      return 'Hi ' + this.firstName;
   },
   determineContext: function() {
      return this === person;
   },
   language: {
      javaScript: function() {
         return `${this.firstName} likes JavaScript!`;
      },
      determineContext: function() {
         return this === person;
      },
      thisInLanguageObject: function() {
          return this;
      }
   }
};
person.determineContext(); // true

Inside person object, the value of this is pointing to the Person object because that's what this do.

Now let's look inside the language object for the value of this

person.language.javaScript(); // "undefined likes JavaScript!"

Inside the language object, there's no firstName property, so this.firstName is undefined.

Q. Does this.firstName === language.firstName inside the language object?

Moving on, let's look at the value of this inside the language object.

person.language.determineContext(); // false

We can be sure that this inside the language object is not pointing to the person object.

So let's see what is the value of this

person.language.thisInLanguageObject();
// {javaScript: Ζ’, determineContext: Ζ’, thisInLanguageObject: Ζ’}

Let's Wrap UP

  • this points the current object it belongs to
  • if this is in global context then this points to the window object
  • if this is in the declared object then this points to that declared object

And this concludes our first two rules.
In the next part, we will see how call, apply and bind works with this and also talk about new keyword in JavaScript.

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.