Advantage of using window prefix in javascript

Are there any advantages to using the window prefix when invoking javascript variables or methods in a window object? For example, if calling "window.alert" took precedence over just calling "alert"? I can imagine that using a prefix can give a slight performance boost when calling some function / object from within, however, I rarely see this in people's code. Henceforth this question.

+5
source share
7 answers

I doubt there is any measurable performance advantage. After the entire chain of scopes is checked for the identifier windowfirst, then the window object will be scanned for the desired element. Therefore, it is more likely that this will constrain performance.

Using a window prefix is ​​useful if you have another variable in scope that will hide an element that you might want to extract from the window. The question is, can you always know when it can be? The answer is no. So you should always prefix with a window? What would you look like if you did. Ugly. Therefore, do not do this if you do not know what you need.

+6
source

. , GlobalObject , :

if(GlobalObject) { // <- error on this line if not defined
    var obj = new GlobalObject();
}

:

if(window.GlobalObject) { // Yay! No error!
    var obj = new GlobalObject();
}

:

if(globalValue == 'something') // <- error on this line if not defined
if(window.globalValue == 'something') // Hurrah!

if(globalObj instanceof SomeObject) // <- error on this line if not defined
if(window.globalObj instanceof SomeObject) // Yippee! window.prop FTW!

, , , - , ( , ).

+7

Google (http://www.techotopia.com/index.php/JavaScript_Window_Object):

window - . , , script , JavaScript window. , , window alert() . . :

window.alert()
()

, : (http://www.javascriptref.com/reference/object.cfm?key=20)

, , - . , Document , Window (, open), Window. "". Window .

+5

, , AnthonyWJones .

, - . , , - , , - :

(function(){
    function foo(){
        //not globally available
    }
    function bar(){
        //not globally available        
    }
    window.baz = function(){
        //is globally available
        foo();
        bar();
    };
})();
+1

, , .

0

, javascript- , window.

0

When you use a prefix, you make it explicit, you use a "global" variable definition, not a local one. (I'm not sure that / how you can embed variables in a scope in JS, except for the weird thing with this and the built-in event handlers.) YMMV, you can either choose clarity or find it just a mess.

0
source

All Articles