The JavaScript this keyword(Interview)

Photo by Zachary Keimig on Unsplash

We will understand the use of this keyword in Javascript. The this keyword has various values that depends where it is used.

  1. In a method, this refer to owner object

For Example

const myName={firstName:"Alok",lastName:"Kumar",fullName:function(){document.getElementById("demo").innerHTML = this; // [object Object]console.log("the this keyword",this); // the this keyword Object {  firstName: "Alok", lastName: "Kumar", fullName: fullName() }return this.firstName+" "+this.lastName;}}console.log("My full Name is ",myName.fullName()) //My full Name is  Alok Kumar

2. Alone, this refers to the global object.

For Example

// this Alone refers to Global object [object Window]const x=thisdocument.getElementById("demo").innerHTML=x;
Photo by Alok Vscode Example
Browser Output

3. In a function, this refers to the global object.

// this in a functionfunction myFunction(){console.log("this in a function") //this in a functiondocument.getElementById("demo").innerHTML=this;}myFunction();

4. In a function, in strict mode, this is undefined

"use strict"function myFunction(){console.log("this in a fucntion in strict mode",this); //this in a fucntion in strict mode undefineddocument.getElementById("demo").innerHTML=this}myFunction(

5. Methods like call(), and apply() can refer this to any object.

// Methods like call(), and apply() can refer this to any object.const myName={firstName:"Alok",lastName:"Kumar",fullName:function(id){const fullName= this.firstName + " " + this.lastName;document.getElementById(id).innerHTML=fullName;return fullName;}}const rameshName={firstName:"Ramesh",lastName:"Kumar",}console.log(myName.fullName("demo")) // Alok Kumarconsole.log(myName.fullName.call(rameshName,"other")) // Ramesh Kumar

--

--