Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptJavaScript this Keyword

JavaScript this Keyword

JavaScript this keyword always holds the reference to a single object, which defines the current line of code’s execution context which means this keyword refers to the object that is currently executing the code. Functions in JavaScript, are essentially objects. Like objects, they can be assigned to variables, passed to other functions, and returned from functions. And much like objects, they have their own properties. 

The value that this store is the current execution context of the JavaScript program. Thus, when used inside a function this value will change depending on how that function is defined, how it is invoked, and the default execution context. this keyword will refer to different objects depending on how it is used. 

There are various ways to set this in JavaScript:

  • Implicit binding 
  • Explicit binding
  • Default binding
  • Arrow function binding

Implicit Binding: When we call a function as a method of the object this keyword refers to the calling object

Example: In this example, we will see the implicit binding of this keyword.

Javascript




const person = {
    name: "ram",
    age: 22,
    greet: function(){
        return `Hello ${this.name}, you are ${this.age} years old`
    }
}
console.log(person.greet());


Output: Here this keyword is referring to the person object so it can access name and age values.

Hello ram, you are 22 years old

Explicit Binding: When we explicitly bind this keyword using the call(), bind(), or apply() method then this keyword default reference is changed to the object called using the above-specified methods.

Example: In this example, we will see the explicit binding of this keyword.

Javascript




function ageVerify(){
    if(this.age> 18){
        console.log("Yes you can drive");
    } else {
        console.log("No you cannot drive");
    }
}
  
const per1 = {age: 21};
const per2 = {age: 16};
ageVerify.call(per1);
ageVerify.call(per2);


Output: We can see that when we use call() method in the function call for two different objects the reference of this is changed in each case. This is how we can explicitly define where this keyword will refer.

Yes you can drive
No you cannot drive

Default Binding: When this keyword is used in global scope this is set to window object.

Javascript




const age = 22;
function verifyAge (){
    return this.age;
}
  
console.log(verifyAge());


Output: We can see that the object this refers to is window and it does not contain the age variable so we get undefined as output.

undefined

Arrow Function Binding: When this is used in the arrow function then this has lexical scope so without the function keyword this is uanble to refer to the object in the outer scope. 

Javascript




const person = {
    name: "ram",
    age: 22,
    greet : () =>{
        return `Hello , you are ${this.age} years old`
    }
}
console.log(person.greet());


Output: We can see that this keyword is unable to refer to the object

Hello , you are undefined years old

The precedence order of this keyword is:

We can see that explicit binding has higher precedence than Other inbuilt bindings.

What this returns depends on where it has been used?

Let us look at different positions where this keyword can be called.

  • this alone
  • this in function
  • this in strict mode
  • this in event handlers

Example of this alone: Refers to the window object.

Javascript




console.log(this)


Output: We can see that this alone refers to the window object in the global scope.

Window {window: Window, self: Window, document: document, name: '', location: Location, …}

Example of this in function: Refers to the global object if it is declared in the global context

Example:

Javascript




function demo(){
    return this;
}
console.log(demo());


Output: Here, also this keyword returns the window object. 

Window {window: Window, self: Window, document: document, name: '', location: Location, …}

Example of this in strict mode:

Javascript




(function(){
    "use strict";
    console.log(this);
})();


Output: In JavaScript, this keyword in global scope is undefined.

undefined

Example of this in event handlers: Refers to the current element that it has received.

HTML




<button onmouseover="this.style.color='green'">
    Hover to change color
</button>


Output: this keyword here received the button element

 

Supported Browser:

  • Google Chrome
  • Microsoft Edge
  • Firefox
  • Opera
  • Safari

We have a complete list of JavaScript reserved words, to learn about them please refer to JavaScript | Reserved Words article.

RELATED ARTICLES

Most Popular

Recent Comments