How the Keyword “this” Works

It’s essential to know that in JavaScript, the keyword this operates differently in comparison with other programming languages. This snippet is there to help you find out where it works and how.

The value of this in JavaScript is determined by the invocation context of the function (context.function()) , as well as where it is called.

The Usage of this in Global Context

In the event of using this in the global context, it is bound to the global object.

Here is an example:

console.log(this); //[object Window]

If you use this within a function defined in the global context, it is still bound to the global object.

The example looks like this:

function func() {
  return this;
}
console.log(func()); //[object Window]

The method of the global object is above func.

It can also be invoked on window object, like this:

<!DOCTYPE html>
<html>
  <body>
    <script>
      function func() {
        return this;
      }
      alert(window.func()); //[object Window]      
    </script>
  </body>
</html>

Inside the Object Method

In the case of using this keyword inside an object method, it is bound to the immediate enclosing object, as follows:

var obj = {
  name: "obj",
  func: function () {
    return this + ":" + this.name;
  }
};
console.log(obj.func()); //[object Object]:obj

Invoking Context-Less Function

If you use this inside a function that is called without any context, it is bound to the global object.

The example looks like this:

<!DOCTYPE html>
<html>
  <body>
    <script>
      var context = "global";
      var obj = {
       context: "object",
       method: function () {
         function func() {
           var context = "function";
           return this + ":" + this.context;
         };
         return func(); //invoked without context 
       }
      };
      alert(obj.method()); //[object Window]:global
    </script>
  </body>
</html>

Inside the Constructor Function

If the function is used as a constructor (when called with the new operator), this inside the function body shows the new object being constructed.

Here is an example:

var varName = "global context";
function SimpleFunction() {
  this.varName = "Simple Function";
}
var obj = new SimpleFunction(); //adds varName to obj 
//1. `new` causes `this` inside the SimpleFunction() to point to the 
// object being constructed thus adding any member 
// created inside SimipleFunction() using this.memberName to the 
// object being constructed 
//2. And by default `new` makes function to return newly 
// constructed object if no explicit return value is specified 
console.log(obj.varName); //Simple Function

Inside the Function Defined On the Prototype Chain

In case the method is on an object prototype chain, this inside it relates to the object the method was executed on as if it is defined on the object.

The example looks like this:

var ProtoObject = {
  func: function () {
    return this.a;
  }
}; //Object.create() creates object with ProtoObject as its
 //prototype and assigns it to obj, thus making func() 
//to be the method on its prototype chain 
var obj = Object.create(ProtoObject);
obj.a = 999;
console.log(obj.func()); //999 
//Notice that fun() is defined on obj's prototype but 
//`this.a` inside fun() retrieves obj.a

Inside the Call(), Apply() and Bind() Functions

The methods such as Call, Apply, and Bind are described in Function.prototype.

These methods allow writing a function once and invoke it in many contexts. In other words, they help to specify the value of this that may be used while the function is being invoked.

  • The func.apply(obj1 [, argsArray]) can set the obj1 as the value of this inside func() calling func() and passing the elements of argsArray like its elements.
  • The func.call(obj1 [, arg1 [, arg2 [,arg3 [, ...]]]]) can set the obj1 as the value of this inside func() calling func() passing arg1, arg2, arg3, … like its arguments.
  • The fun.bind(obj1 [, arg1 [, arg2 [,arg3 [, ...]]]]) can return the reference to the function func using this within func bound to obj1, as well as the parameters of func bound to the parameters such as arg1, arg2, arg3,... .

Inside Arrow Functions

In the arrow functions, this operates like standard variables. It is inherited from its lexical scope.

It looks the same as here:

(function () {}).bind(this)

Also, take a look at the following code:

const globalArrowFunction = () => {
  return this;
};
console.log(globalArrowFunction()); //window 
const contextObject = {
  method1: () => {
    return this
  },
  method2: function () {
    return () => {
      return this
    };
  }
};
console.log(contextObject.method1()); //window
const contextLessFunction = contextObject.method1;
console.log(contextLessFunction()); //window
console.log(contextObject.method2()()) //contextObject 
const innerArrowFunction = contextObject.method2();
console.log(innerArrowFunction()); //contextObject

So, the operator this plays a vital role in JavaScript. It is also one of the misunderstood concepts of JavaScript as it behaves differently in other programming languages. Naturally, it refers to the owner of the function that is being currently executed.


Do you find this helpful?

Related articles