Easy Tutorial
❮ Js Functions Js Window Screen ❯

JavaScript this Keyword

In object-oriented languages, this represents a reference to the current object.

However, in JavaScript, this is not fixed and can change depending on the execution context.

Example

var person = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

this in Methods

In an object method, this points to the object that invoked the method.

In the above example, this refers to the person object.

The fullName method belongs to the person object.

Example

fullName : function() {
  return this.firstName + " " + this.lastName;
}

this Alone

When used alone, this refers to the global object.

In a browser, the global object is [**object Window**]:

Example

var x = this;

In strict mode, when used alone, this also refers to the global object.

Example

"use strict";
var x = this;

this in Functions (Default)

In a function, the default binding of this is to the global object.

In a browser, the global object is [**object Window**]:

Example

function myFunction() {
  return this;
}

this in Functions (Strict Mode)

In strict mode, this is not bound to the function and is undefined.

Example

"use strict";
function myFunction() {
  return this;
}

this in Events

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

Example

<button onclick="this.style.display='none'">
  Click me to disappear
</button>

Binding in Object Methods

In the following example, this is the person object, which is the owner of the function:

Example

var person = {
  firstName  : "John",
  lastName   : "Doe",
  id         : 5566,
  myFunction : function() {
    return this;
  }
};

Example

var person = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

Note: this.firstName refers to the firstName property of the this (person) object.


Explicit Function Binding

In JavaScript, functions are objects and have methods, including apply and call. These methods allow changing the context (this binding) of function execution.

In the following example, when we call person1.fullName with person2 as an argument, this points to person2, even though it's a method of person1:

Example

var person1 = {
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
}
var person2 = {
  firstName:"John",
  lastName: "Doe",
}
person1.fullName.call(person2);  // Returns "John Doe"
❮ Js Functions Js Window Screen ❯