I recently learned that you don't have to pass the event as a parameter for an event. But I wonder why many still pass the event.
Example click event
btn.addEventListener("click", myfn.bind());
function myfn(event) {
console.log(event.target);
console.log(this);
}
Is there a reason for this? Because that works to:
btn.addEventListener("click", myfn.bind());
// without passing event
function myfn() {
console.log(event.target);
console.log(this);
}
CodePudding user response:
btn.addEventListener("click", myfn.bind());
// without passing event
function myfn() {
console.log(event.target);
console.log(this);
}
Above works because event
can access through a global variable, window.event
The read-only Window property event returns the Event which is currently being handled by the site's code. Outside the context of an event handler, the value is always undefined.
function myfn(anotherArgName) {
console.log(anotherArgName === window.event); // true
}
Not recommend to use the 2nd one as MDN docs says,
Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
Plus depending on external dependencies makes your function hard to read, test & maintain.