Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

javascript - Is event a global variable that is accessible everywhere inside the callback chain?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One can access the current event through window.event. Just using event is implicitly accessing window.event.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...