this keyword Practical Example in js

this keyword Practical Example in js

This keyword in JS is a very confusing topic for beginners mostly beginner JS developer got confused about using this keyword, when to use, how to use. Here I am explaining an easy concept to understand this keyword easily.

1. this keyword has multiple elements:  this keyword is used when you have multiple elements, and you want to point out that element on which you have applied an event.

Example: In this example, we will see, we have multiple small images, and we will replace the small image with an extensive image on which the image has been clicked. This example looks like the Flipkart product detail page image section.

<!DOCTYPE html>
<html>
<head>
</head>
 
<body>
 
<p><img src="images/2.jpeg"  style="width:300px" id="bigimg"></p>
 
<img src="images/2.jpeg" onclick="changeimage(this.src)" title="hello" style="width:100px">
<img src="images/1.jpeg" onmouseover="changeimage(this.src)" style="width:100px">
<img src="images/3.jpeg" onmouseover="changeimage(this.src)" style="width:100px">
<img src="images/4.jpeg" onmouseover="changeimage(this.src)" style="width:100px">
<img src="images/5.jpeg" onmouseover="changeimage(this.src)" style="width:100px">
<img src="images/6.jpeg" onmouseover="changeimage(this.src)" style="width:100px">
<img src="images/7.jpeg" onmouseover="changeimage(this.src)" style="width:100px">
 
 
 
<script>
function changeimage(smallimgsrc)
{
  document.getElementById("bigimg").src=smallimgsrc;
}
</script>
 
</body>
</html>

In this example, change your src with your source. Here, src gives an src of an image on which we have applied a click event.

 

2. this keyword with class:  When we use class, we have needed this keyword to access the variable and method of the class. This keyword here points to a variable or method of that class.

Example:  

<!DOCTYPE html>
<html>
<body>
 
<h2>JavaScript Class</h2>
 
<p>How to use a JavaScript Class.</p>
 
<p id="demo"></p>
 
<script>
class Car {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }
}
 
const myCar = new Car("Ford", 2014);
document.getElementById("demo").innerHTML =
myCar.name + " " + myCar.year;
</script>
 
</body>
</html>