In a web browser at this address: https://www.w3schools.com/js/tryit.asp?filename=tryjs_arrow_function6 , I deleted the original code, and pasted this code:
<!DOCTYPE html>
<html>
<body>
<button id="btn">Click Me!</button>
<p id="demo"></p>
<script>
document.getElementById("btn").addEventListener("click", function() {
console.log(this) // **THIS LINE GAVE THE VALUE OF AS BUTTON**
});
</script>
</body>
</html>
In React Stackblitz a tried this code:
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
class Foo extends React.Component{
render(){
return (
<button type="button" onClick={function handleClick(event){
console.log(this); // **THIS LINE GAVE THE VALUE AS UNDEFINED**
}}>
Click Me
</button>
);
}
}
render(<Foo />, document.getElementById('root'));
Why are the two results different? Please refer to the comments of both code samples. The first code logged to the console the button as the value of this, the second code logged to the console undefined as the value of this. Shouldn't they be the same? Why are they different?