This Keyword in JavaScript

This keyword refers to an object, that object which is executing the current bit of JavaScript code.

JavaScript function while executing has a reference to its current execution of any function, called this.

JavaScript function while executing has a reference to its current execution of any function, called this.

with this keyword, It does not matter how and where the function is declared or defined.

Example

function’s this keyword behaves differently in JavaScript compared to another language.

In most cases, this it is determined by how value of the function is called.

It cannot be set by assignment on-time execution, and it will be different each time the function is called.

ES5 have the bind() method to set the value of a function’s this regardless of how it’s called, and ES2015 introduced arrow functions that don’t provide their own this binding.

Example

This keyword has some different values depending on its usage:

  • Within a method, this keyword refers to the owner object.
  • As Single, this keyword refers to the global object.
  • this keyword within a function refers to the global object.
  • Within a function, within the strict mode, this keyword is undefined.
  • Creating an event, this keyword refers to the element that received the event.
  • Methods like call(), and apply() can refer to any object.

In an object method, this refers to the “owner” of the method.

In the example on the top of this page, this refers to the person object.

The person object is the owner of the fullName method.

Example

OUTPUT

This in Event Handlers

In HTML event handlers, this refers to the HTML element that received the event:

This in a Function (Default)

The owner of the function is the default binding for this.

Within function, this keyword refers to the Global object.

OUTPUT

Global Scope

If a function uses ‘this’ keyword, is called from the global scope then this will point to the window object

OUTPUT

Example: this keyword inside inner function

OUTPUT