You don't need to pass this
, there already is the event
object passed by default automatically, which contains event.target
which has the object it's coming from. You can lighten your syntax:
This:
<p onclick="doSomething()">
Will work with this:
function doSomething(){
console.log(event);
console.log(event.target);
}
You don't need to instantiate the event
object, it's already there. Try it out. And event.target
will contain the entire object calling it, which you were referencing as "this" before.
Now if you dynamically trigger doSomething() from somewhere in your code, you will notice that event
is undefined. This is because it wasn't triggered from an event of clicking. So if you still want to artificially trigger the event, simply use dispatchEvent
:
document.getElementById('element').dispatchEvent(new CustomEvent("click", {'bubbles': true}));
Then doSomething()
will see event
and event.target
as per usual!
No need to pass this
everywhere, and you can keep your function signatures free from wiring information and simplify things.
Update 2022-10-30:
I have contacted someone from WHATWG, and another way it could be done is below, although some IDE's report it as "obsolete" which it's not. You could pass the "event" keyword (no capital E) in your caller's argument list, in any position, and use it as such.
Below would work, a, b, c and d being extra arguments to pass if any, to demonstrate the order doesn't matter:
<p onclick="doSomething(a,b,event,c,d)">
And in your function definition, you would capture it accordingly:
function doSomething(arg1, arg2, arg3, arg4, arg5){} //arg3 would contain the event
And access the usual properties, in this case since we wired event with arg3:
console.log(arg3.target)