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
251 views
in Technique[技术] by (71.8m points)

javascript - Why the subtle cross-browser differences in Event Object

The following declaration at the window level:

    var event; // for IE
    var event = "anything"; // for Chrome

will destroy the event object as used here:

    <div onMouseOver = "alert(event.type);">Mouseover Div</div>

Firefox does not seem phased by either declaration.

I realize that declaring a variable with the name "event" is bad code but I am curious about the technical difference here, e.g. that the use of var in IE reinitializes the variable to null, whereas Chrome will not overwrite with a var declaration unless a value is explicitly assigned, and maybe FF holds the event object outside of the window's var declaration scope altogether.

This is more of a curiosity. I ran into a bug in IE on a site outside of my control that was caused by this and the more I looked into the more I saw subtle differences between browsers. Just wondering if anyone had any insights here.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In IE, event is a property of the window object and is used in event handlers functions to access the event being handled. In other browsers such as Firefox, the situation is that in an event handler attribute, the JavaScript code inside the attribute is called as though it forms the body of a function into which has been passed a parameter called event that corresponds to the event being handled. So in

<div onmouseover="alert(event.type);">Mouseover Div</div>

the mouseover code is effectively

function(event) {
    alert(event.type);
}

and the event parameter overrides any event declared in a containing scope, whereas in IE, it's

function() {
    alert(event.type);
}

and the event identifier is resolved as a property of the global object (i.e. window).


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

...