Loading, please wait...

MCQ

What is 'this' keyword in JavaScript?

this references the object executing the current function. Many are not aware of the this keyword in JavaScript due its very different functionality. The this keyword is basically used for calling some function by determining it, much like binding it.

What is this keyword in JavaScript?

this references the object executing the current function. Many are not aware of this keyword in JavaScript due to its very different functionality. This keyword is basically used for calling some function by determining it, much like binding it. With this keyword, we can refer to an object pointing to a method or bind functions and objects together or refereeing to the global object present in the window.

Object Method Binding

Like for instance, if we declare an object, with  a function inside it then,

const objectOne = {

  name: "zack",

  hello() {

    console.log(this);

  },

};

After putting this in the console log it means that it is binding the following function with the parent object.

Let us call the function and see the result.

objectOne.hello();

 

 

 

 

 

 

We can see that this keyword helped us to call the function from outside and also linked the parent object.

Now let us try fetching data from the object inside a function with this keyword.

Example:

const objectOne = {

  name: "zack",

  age: '19',

  place: 'delhi',

  hello() {

    var info = `The name is ${this.name} whose age is ${this.age} and lives in ${this.place}`

    console.log(info);

  },

};




objectOne.hello();

In the above code, there is some info inside the object which is then called inside the function and after calling the function it will show the whole sentence.

 

 

 

Global Object

When working with this keyword, by default it will refer to the window object, if it is not mentioned or allocated any value.

Example:

function video(name){

    this.name = name;

    console.log(this)

}

const HelloHi = new video('shibam');

this in Event Handlers

This keyword comes in real handy while working with JavaScript event listeners. It can be used to add classes, remove elements, give styling, and many more. In an event, this refers to the element that received the event.

Example:

<button onclick="this.style.color='red'">Click to Remove Me!</button>

Before click 

 

 

After click.

 

 

NOTE:  While working with this keyword, make sure to keep in mind that while working in a method or object it will have the lowest scope or the child scope but in a function, it will refer to the global scope.

Example:

const objectOne = {

  name: "zack",

 tags:[ ‘a’, ‘b’, ‘c’},

  hello() {

    this.tags.forEach(function(tag){

                console.log(this, tag);

})

  },

};




objectOne.hello();

In the above code, this will display the objects present globally in the window and the tag will show all the tags from the tags array.

MCQ

Related Article