0 votes
in JavaScript by
Explain “this” keyword.

1 Answer

0 votes
by

The “this” keyword refers to the object that the function is a property of.

The value of “this” keyword will always depend on the object that is invoking the function.

Confused? Let’s understand the above statements by examples:

function doSomething() {

  console.log(this);

}

        

doSomething();

What do you think the output of the above code will be?

**Note - Observe the line where we are invoking the function.

Check the definition again:

The “this” keyword refers to the object that the function is a property of.

In the above code, function is a property of which object?

Since the function is invoked in the global context, the function is a property of the global object.

Therefore, the output of the above code will be the global object. Since we ran the above code inside the browser, the global object is the window object.

Example 2:

var obj = {

    name:  "vivek",

    getName: function(){

    console.log(this.name);

  }

}

        

obj.getName();

In the above code, at the time of invocation, the getName function is a property of the object obj , therefore, the this keyword will refer to the object obj , and hence the output will be “vivek”.

Example 3:

 var obj = {

    name:  "vivek",

    getName: function(){

    console.log(this.name);

  }

        

}

        

var getName = obj.getName;

        

var obj2 = {name:"akshay", getName };

obj2.getName();

Can you guess the output here?

The output will be “akshay”.

Although the getName function is declared inside the object obj , at the time of invocation, getName() is a property of obj2 , therefore the “this” keyword will refer to obj2 .

The silly way to understanding the this keyword is, whenever the function is invoked, check the object before the dot . The value of this . keyword will always be the object before the dot .

If there is no object before the dot like in example1, the value of this keyword will be the global object.

Example 4:

var obj1 = {

    address : "Mumbai,India",

    getAddress: function(){

    console.log(this.address); 

  }

}

       

var getAddress = obj1.getAddress;

var obj2 = {name:"akshay"};

obj2.getAddress();    

Can you guess the output?

The output will be an error.

Although in the code above, the this keyword refers to the object obj2 , obj2 does not have the property “address”‘, hence the getAddress function throws an error.

Related questions

+1 vote
asked Jan 26, 2022 in Usability Principles by sharadyadav1986
0 votes
asked Sep 28, 2023 in JavaScript by AdilsonLima
...