Home » javascript » This Keyword in JavaScript

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 any function, called this.

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

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

Example

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

In most of cases, this is determined that by how avalue of 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 which 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 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 this 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

Submit your review
1
2
3
4
5
Submit
     
Cancel

Create your own review

Ebhor.com
Average rating:  
 1 reviews
by Anonymous on Ebhor.com

good quality

Managed by MochaHost - Fast & Easy WordPress Hosting