DEV Community

Cover image for Understanding 'this' in javascript.
Sage
Sage

Posted on

Understanding 'this' in javascript.

To better understand 'this' keyword in javascript, we need to have a mental model of how code execution happens in javascript.
Each time javascript code is executed, an 'Execution Context' is created by default. This is known as Global Execution Context.

Each time a function is executing, a new execution context is created for that function, This can be called Function Execution Context.

Think of execution context as a box, some container, and inside of it is information about the code that is currently executing and the environment around it. Information like, what variables are declared inside this executing code, what is the value of 'this', what is the global object, what other code surround this executing function. Are you with me? Okay.

Part of a function's execution context is a reference to the value of 'this'. What this means is that every execution context has a value for 'this' and this value is set by the javascript engine by default depending on how the function was called(More on this later) and it may be different each time the function is executing. So we can say 'this' is a property of the execution context.

'this' always points to an object in non-strict mode, and points to undefined in strict mode. It points to the object that is in charge of the currently executing function, that is the object the function was called on.

a)
function greet() {
  console.log(this); 

}

greet(); // Window {...} in a browser
Enter fullscreen mode Exit fullscreen mode
b)
const boy = {
  name: 'Sage',
  greet() {
    console.log(this); 
  }
};

boy.greet(); // { name: 'Sage', ...}

Enter fullscreen mode Exit fullscreen mode

As you can see from the snippet above, In javascript how and where you call a function is more important than where it was defined, one reason is that it determines the value of 'this' in that execution context.

In a) 'this' points to the global object because it's not executed on an object and is executed in the global scope.

function greet() {
  console.log(this); 

}

greet(); // Window {...} in a browser
Enter fullscreen mode Exit fullscreen mode

In b) Since 'greet' method was called on an object, it's 'this' defaults to the object it's called on.

const boy = {
  name: 'Sage',
  greet() {
    console.log(this); 
  }
};

boy.greet(); // { name: 'Sage', ...}
Enter fullscreen mode Exit fullscreen mode

Any method called on an object automatically has its 'this' set to that object by default.

Functions not called on an object have their 'this'* set by default to the global object (Window object in the browser). This behavior is similar for arrow functions.

To set a 'this' value explicitly, use the

javascript .bind()

method. It creates a new function that has it's 'this' bound to the object passed to it.

Also see this, How to use bind in javascript.

Top comments (0)