React “This” Keyword
Regular Function
© The “this” represents the object that called the
function.
© It means there is an different objects depending on how
the function was called, which could be the window, the document, a button (or)
Whatever.
Just save as normal html
file react.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>ReactJS</title>
</head>
<body>
<button id="btn">Click Me!</button>
<h1 id="myheading">Its Heading Tag</h1>
<div id="mydiv">Its Div Tag</div>
<p>In Regular Function the <b>this </b>keyword
represents</p>
<p id="demo"></p>
</body>
<script>
class RegvsArr{
changeColor =function(){
document.getElementById("demo").innerHTML+=this;
}
}
var regvsarr=new RegvsArr();
//The Window object calls the function
window.addEventListener("load",regvsarr.changeColor);
//A button object calls the function
document.getElementById("btn").addEventListener("click",regvsarr.changeColor);
//A div object calls the function
document.getElementById("mydiv").addEventListener("click",regvsarr.changeColor);
//A heading object calls the function
document.getElementById("myheading").addEventListener("click",regvsarr.changeColor);
</script>
</html>
Output
Arrow Function
© The “this” keyword always represent the object that
defined the arrow function.
© No matter who called the function.
Just save as normal html file react.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>ReactJS</title>
</head>
<body>
<button id="btn">Click Me!</button>
<h1 id="myheading">Its Heading Tag</h1>
<div id="mydiv">Its Div Tag</div>
<p>In Regular Function the <b>this </b>keyword
represents</p>
<p id="demo"></p>
</body>
<script>
class RegvsArr{
changeColor =()=>{
document.getElementById("demo").innerHTML+=this;
}
}
var regvsarr=new RegvsArr();
//The Window object calls the function
window.addEventListener("load",regvsarr.changeColor);
//A button object calls the function
document.getElementById("btn").addEventListener("click",regvsarr.changeColor);
//A div object calls the function
document.getElementById("mydiv").addEventListener("click",regvsarr.changeColor);
//A heading object calls the function
document.getElementById("myheading").addEventListener("click",regvsarr.changeColor);
</script>
</html>
Output
No comments:
Post a Comment