You are currently viewing What is this Keyword in JavaScript With Example

What is this Keyword in JavaScript With Example

Javascript this Keyword With Example

In this article, we will see about javascript this keyword with example.

What is this Keyword

  • this is a special keyword present inside every constructor function & method.
  • this is a reference variable, which always points to the object with which we are currently working
  • It is used to access members(i.e attributes & behaviors) of the currently working object.

Example code

function Rectangle(width, height){
this.width = width;
this.height = height;
this.getArea = function()
return this.width*this.height;
} }

var rect1 = new Rectangle(5,5);

var rect2 = new Rectangle(6,6);

  1. Here we have the create function “Rectangle” with passing two-parameter (width, height).
  2. In the function, we assign the width value to this. width and height value to this.height.
  3. Then we create another function within the “Rectangle” function() and return this.width * this.height value inside the function.
  4. We need to create a variable to call the function as in the above code. Here, we create variable ‘rect1’ and then call the Rectangle() function by passing two arguments (5,5).
  5. Then we need to print the variable to call the getArea() function because the geArea() function has a return value.
READ ALSO  Relational Operators in Javascript With Example

Leave a Reply