const Event = () => {
// useEffect(()=>{
// document.getElementById('btn').addEventListener('click', function() {
// console.log(myObj.showThis())
// })
// })
const myObj = {
name: 'romeo',
showThis: function() {
console.log(this)
}
}
return (
<div>
<button id='btn' onClick={myObj.showThis} >Fire Event</button>
</div>
)
}
In here, I am adding inline event handler which invokes the myObj.showThis
method, and when it does, the console logs out undefined, but if I instead use the useEffect()
hook to add event listener to the button, which invokes the same myObj.showThis
function, now the console logs out the caller, which is the button, so this
refers to the caller, but why is this
undefined when I invoke the same method via inline event handler?