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>

Categories: web designing javascript

Trending Courses

CodeIgniter

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Advance Digital Marketing

Regular : 6 Months

Fastrack : 3 Months

Crash : 2 Months

React JS

Regular : 45 Days

Fastrack : 20 Days

Crash : 7 Days

Laravel

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Front End Developer

Regular : 7 Month

Fastrack : 4 Month

Crash : 2 Month

Related Blogs

Request For Demo