JavaScript: 'this' in functions and methods.

JavaScript: 'this' in functions and methods.

Having a good grasp of 'this' cannot be avoided in JS, here's a simple breakdown of 'this' and its caveats.

Put simply, the this keyword refers to an object, which is executing the current code. Every JS function when being executed has a reference to its current execution context i.e this.

To understand the this keyword, we need to know how, when and where is the function being called regardless of where the function is being declared.

Window/Global Object:

The window object in a browser is the default global object created by the JS engine, which contains various objects and methods that can be accessed by the user.

window.PNG

this in the browser console refers to the window which is itself the object in which we currently are. window is created along with the global execution context.

When we run code in JS, the JS engine creates:

  • A global execution context.
  • A global object, in this case, Chrome V8 Engine creates a window.
  • A this variable is created.

Points to note:

Here, this points to the window object as we're in the global context.

thiswindow.PNG

And every time an execution context is created a this is created with it.

Rules of thumb for this:

  1. For all regular function calls, this points to the global object.
  2. For all functions that are inside an object i.e. methods, this references to that object itself.

Let's see how these rules apply in different examples.

const blogFunction () {
console.log(this) 
}

blogFunction()

Rule 1. straightforwardly applies here and as we're doing a regular function call, the window object is printed onto the console.

const blog = {
  blogTitle: "closures",
  postBlog() {
    console.log(this);
  },
};

blog.postBlog();
  • In this example, we are invoking a method postBlog.
  • Rule 2. applies here, since invoking a method is not a regular function call, it's through an object and this will point towards the object blog.

blogthis.PNG

Now, let's add another function inside the method postBlog:

const blog = {
  blogTitle: "closures",
  postBlog() {
    console.log(this);
    function editBlog() {
      console.log(this);  
    }
  editBlog()
  },
};

blog.postBlog();

As this is a common use case of function calls inside methods in JS, it is important to understand how this behaves.

  • this in method postBlog points towards the object blog as we discussed in the previous example.

  • Interestingly, this inside the function editBlog points towards the window object although it is present inside the method postBlog

funcinsidemethod.PNG

  • This is because editBlog is being called as a regular function, and according to the first rule, this in a regular function call will always point towards the window.

this and Arrow Functions:

Using this with an arrow function is quite different from using it with any other kind of JavaScript function. An arrow function uses the this value from its enclosing execution context, since it does have one of its own.

this in an arrow function is always the same as this around it (in its immediate scope). So, if you use arrow functions within an object method, the this context stays as the object, not window.

  • Let's change the previous inner function to an arrow function and run it:
const blog = {
  blogTitle: "closures",
  postBlog() {
    console.log(this);
    let editBlog = () => {
      console.log(this);
    }
    editBlog();
  },
};

blog.postBlog();

arrowclosures.PNG

This time we don't get the window object on calling editBlog() as it assumes the this context of it's enclosing scope i.e. the this of postBlog which is the object blog.

  • Making the postBlog function an arrow function itself changes the this behavior as follows:
const blog = {
  blogTitle: "closures",
  postBlog: () => {
    console.log(this);
    let editBlog = () => {
      console.log(this);
    }
    editBlog();
  },
};

blog.postBlog();

arrowthis.PNG

Here, this in postBlog itself points towards window and hence the inner function editBlog also points towards window as it assumes the this context of its immediate scope.

the above rules of thumb for this can help us avoid these confusion traps.

thank you for reading!

I will list down some more resources on this should you want to learn more and explore further:

References:

JS this keyword by Mosh:

Another accurate explanation on this by Hitesh Choudhary:

More on window by Akshay Saini:

call,apply,bind by Akshay Saini:

Some more caveats on this by Rajat S: blog.bitsrc.io/what-is-this-in-javascript-3..