Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefit of using 'window' prefix in javascript

Are there any benefits to using the 'window' prefix when calling javascript variables or methods in the window object? For example, would calling 'window.alert' have an advantage over simply calling 'alert'? I can imagine using the prefix could give a small performance boost when the call is made from inside some function/object, however I rarely see this in people's code. Henceforth this question.

like image 605
Protector one Avatar asked Jul 17 '09 15:07

Protector one


People also ask

Why do we use window in JavaScript?

A global variable, window , representing the window in which the script is running, is exposed to JavaScript code. The Window interface is home to a variety of functions, namespaces, objects, and constructors which are not necessarily directly associated with the concept of a user interface window.

What does prefix do in JavaScript?

The prefix property sets or returns the namespace prefix of a node.

What is Window value in JavaScript?

window. variableName means that the variable is being declared at the global scope. This means any JS code will have access to this variable. Using window. is not necessary but is frequently used as a convention to denote that a variable is global.


1 Answers

This is useful when attempting to test global object values. For example, if GlobalObject is not defined then this throws an error:

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

but this does not throw an error:

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

Similarly with:

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

and:

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

I would not expect to see a significant performance difference, and the only other reason you might do this is to ensure that you are actually getting a value from the global scope (in case the value has been redefined in the current scope).

like image 94
Prestaul Avatar answered Oct 03 '22 07:10

Prestaul