I was just playing around with event listeners with DOM and Javascript and did notice this:
function chained(msg) {
console.log(msg, event);
}
function onClick() {
chained('the body was clicked');
}
document.body.addEventListener('click', onClick);
Now the funny thing...this will output:
"the body was clicked, (MouseEvent)"
Then I ask, why? how does it passes the event object without sending it on the chained
call?
function chained(msg) {
console.log(msg, namedEventObj); //throw error namedEventObj is not defined
}
function onClick(namedEventObj) {
console.log(event); //outputs (MouseEvent);
console.log(nameEventObj); //outputs (MouseEvent);
chained('the body was clicked');
}
document.body.addEventListener('click', onClick);
Even If I declare the event obj to be passed on the onClick
function as namedEventObj
it will available only to onClick
but not to chained
function...I got this and this makes sense for me...but definitely not the event
variable to be available to the chained
function.
Anyone know why does it behaves like this?
The only thing I can think of is that event is in fact window.event
and it makes itself available when some event dispatches and Event...but that would mean that any element could get that event information if called at the same time as the event when it triggers?
I am using Chrome 11.0.x
window.event
), don't know what there is more to say about that. Of course you can access global variables from everywhere (that's why they are global). – Bassariskfunction(event)
you are thinking that you are sending that and not that it is already automatically sent and don't give the impression that it will spread through all chained function. so I believewindow.event
is easy to comprehend as global...but notevent
which in most cases coincide with the attribute name you pass, but that can't be done since everything is already inside the window anyway...and inherited :( just checked that it does not happen in Gecko tho, but persists for webkit – Elmaevent
, you know it must come from a higher scope (in this casewindow
). And if you pass it asevent
, then you are actually access the parameter and notwindow.event
. So it just works how functions work :) – Bassariskfunction(event) { event = event || window.event;}
. This will takewindow.event
only ifevent
is not defined (which is the case for older IE browsers).window.event
does not work in Firefox. – Bassarisk