开发者

window object acting strange in Chrome and IE

开发者 https://www.devze.com 2023-03-08 04:53 出处:网络
Consider the following开发者_如何学运维 sample HTML: <div id=\"about\"> <!-- content here -->

Consider the following开发者_如何学运维 sample HTML:

<div id="about">
 <!-- content here -->
</div>

And the following script

var about = (function ($, window, document) {
    "use strict";

     var methods;

     methods = {
        init: function () {
        // Do things here 
        }
     };

     return methods;
} (jQuery, window, document));

The variable about should be attached to the window object at this point.

In Firefox (3.6.17) I am able to write

window["about"] 

And if about hasn't been processed yet this will return undefined if it has it will return the object just as I expect.

However, the problem is that that same code window["about"] in Chrome and IE (7 & 8) returns the actual HTML object. From the example above, it would return the following:

    <div id="about">
     <!-- content here -->
    </div>

Why does this happen?

Also, is there a better way to check and see if the about object is available, than using the window element? I realize ideally one doesn't want to junk up the window object but that is a different question all together.

Thanks


The WebKit browsers seem to ape the old IE behavior of treating element "id" values as properties of the window object.

I dislike the behavior, personally.


Chrome will take any ID in the HTML and turn it into a global variable. You can overwrite the assignment, but I assume you're checking for existence and not overwriting perhaps?

http://jsfiddle.net/robert/Hnw7y/


One way to differentiate between the HTMLElement and the function would be to check the object's type:

if (typeof window.about === 'function') {
    // the 'about' function has been defined
}


Unfortunately the only way you can do this is the following:

function global(name) { return eval(name); }

if( global("about") )
   ...

Try this: http://jsfiddle.net/PMqPv/1/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号