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.
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).
I doubt there is any measurable performance benefit. After all the scope chain would be scanned for the identifier window first then the window object would be scanned for the desired item. Hence more likely it would be deterimental to performance.
Using window prefix is useful if you have another variable in scope that would hide the item you may want to retrieve from the window. The question is can you always know when this might be? The answer is no. So should you always prefix with window? What would you code look like if you did that. Ugly. Hence don't do it unless you know you need to.
Retrieved from Google (http://www.techotopia.com/index.php/JavaScript_Window_Object):
The window object is the top-level object of the object hierarchy. As such, whenever an object method or property is referenced in a script without the object name and dot prefix it is assumed by JavaScript to be a member of the window object. This means, for example, that when calling the window alert() method to display an alert dialog the window. prefix is not mandatory. Therefore the following method calls achieve the same thing:
window.alert()
alert()
However, I read but have not had time to test the following from:
(http://www.javascriptref.com/reference/object.cfm?key=20)
One place you'll need to be careful, though, is in event handlers. Because event handlers are bound to the Document, a Document property with the same name as a Window property (for example, open) will mask out the Window property. For this reason, you should always use the full "window." syntax when addressing Window properties in event handlers.
As far as performance, I think AnthonyWJones has it covered.
One use of the window prefix is to explicitly make something available outside the current scope. If you were writing code in a self-invoking function to avoid polluting the global scope, but there was something within that you did want to make globally available, you might do something like the following:
(function(){
function foo(){
//not globally available
}
function bar(){
//not globally available
}
window.baz = function(){
//is globally available
foo();
bar();
};
})();
I imagine that the performance benefit here is amazingly insignificant at best, if there is one at all.
It only matters if you're using frames and doing a bunch of javascript calls across frames, and even then only specific scenarios warrant the necessity of referencing window explicitly.
When you use the prefix, you're making it explicit you're using the "global" definition of the variable, not a local one. (I'm not sure whether / how you can inject variables into a scope in JS, except the weirdness with this and inline event handlers.) YMMV, you may either prefer the clarity, or find it to be just clutter.
Related
Every property of the window object is a global variable. This means you can do something like this:
window.foo = 42;
alert(foo); //alerts 42
var bar = 3;
alert(window["bar"]); //alerts 3
Because of this, I've always wondered what the purpose was of referencing window in code like this
if(window.prompt("Enter Password") === "secret") {
window.location.hash = "authorized";
window.open("secretPage.html");
}
when you could omit window and have code that does exactly the same thing:
if(prompt("Enter Password") === "secret") {
location.hash = "authorized";
open("secretPage.html");
}
The use also seems inconsistent; I almost never see window.alert but I'll frequently see window.location.
Do people just like referencing window to make their code more verbose? Is there some good reason for doing this that I don't know about?
One situation in which it helps to be explicit is that it will be immediately clear inside a function that you intend to modify a global variable. For example:
function blah() {
// a bunch of code preceding...
test = "aha!";
}
Did someone forget to declare test with var? Or is this intentional modification of a global? Compare:
function blah() {
// a bunch of code preceding...
window.test = "aha!";
}
Now it's immediately clear what is intended. Of course, you know, globals should be avoided in the first place, but you get my point.
window is implicit, but it's good code practice to avoid ambiguity where possible.
I think it's generally used to avoid potential clashes with other variables in an enclosing closure. Also, style checkers like jslint will raise errors if you access global properties without an explicit object (except for well-known properties like window itself.)
That said, in a browser, when you get into multiple windows, e.g., with iframes, etc., you may need to explicitly pass around a reference to the window object. (And if you really care about the details, the window object, or at least references to it, are very special and can't even be described in standard javascript.)
Have you ever taken a look under the hood at the jQuery 1.4 source code and noticed how it's encapsulated in the following way:
(function( window, undefined ) {
//All the JQuery code here
...
})(window);
I've read an article on JavaScript Namespacing and another one called "An Important Pair of Parens," so I know some about what's going on here.
But I've never seen this particular syntax before. What is that undefined doing there? And why does window need to be passed and then appear at the end again?
The undefined is a normal variable and can be changed simply with undefined = "new value";. So jQuery creates a local "undefined" variable that is REALLY undefined.
The window variable is made local for performance reasons. Because when JavaScript looks up a variable, it first goes through the local variables until it finds the variable name. When it's not found, JavaScript goes through the next scope etc. until it filters through the global variables. So if the window variable is made local, JavaScript can look it up quicker.
Further information: Speed Up Your JavaScript - Nicholas C. Zakas
Undefined
By declaring undefined as an argument but never passing a value to it ensures that it is always undefined, as it is simply a variable in the global scope that can be overwritten. This makes a === undefined a safe alternative to typeof a == 'undefined', which saves a few characters. It also makes the code more minifier-friendly, as undefined can be shortened to u for example, saving a few more characters.
Window
Passing window as an argument keeps a copy in the local scope, which affects performance: http://jsperf.com/short-scope. All accesses to window will now have to travel one level less up the scope chain. As with undefined, a local copy again allows for more aggressive minification.
Sidenote:
Though this may not have been the intention of the jQuery developers, passing in window allows the library to be more easily integrated in server-side Javascript environments, for example node.js - where there is no global window object. In such a situation, only one line needs to be changed to replace the window object with another one. In the case of jQuery, a mock window object can be created and passed in for the purpose of HTML scraping (a library such as jsdom can do this).
Others have explained undefined. undefined is like a global variable that can be redefined to any value. This technique is to prevent all undefined checks from breaking if someone wrote say, undefined = 10 somewhere. An argument that is never passed is guaranteed to be real undefined irrespective of the value of the variable undefined.
The reason to pass window can be illustrated with the following example.
(function() {
console.log(window);
...
...
...
var window = 10;
})();
What does the console log? The value of window object right? Wrong! 10? Wrong! It logs undefined. Javascript interpreter (or JIT compiler) rewrites it this way -
(function() {
var window; //and every other var in this function
console.log(window);
...
...
...
window = 10;
})();
However, if you get the window variable as an argument, there is no var and hence no surprises.
I don't know if jQuery is doing it, but if you are redefining window local variable anywhere in your function for whatever reason, it is a good idea to borrow it from global scope.
window is passed in like that just in case someone decides to redefine the window object in IE, I assume the same for undefined, in case it's re-assigned in some way later.
The top window in that script is just naming the argument "window", an argument that's more local that the global window reference and it what the code inside this closure will use. The window at the end is actually specifying what to pass for the first argument, in this case the current meaning of window...the hope is you haven't screwed up window before that happens.
This may be easier to think of by showing the most typical case used in jQuery, plugin .noConflict() handling, so for the majority of code you can still use $, even if it means something other than jQuery outside this scope:
(function($) {
//inside here, $ == jQuery, it was passed as the first argument
})(jQuery);
Tested with 1000000 iterations. This kind of localization had no effect in performance. Not even a single millisecond in 1000000 iterations. This is simply useless.
Have you ever taken a look under the hood at the jQuery 1.4 source code and noticed how it's encapsulated in the following way:
(function( window, undefined ) {
//All the JQuery code here
...
})(window);
I've read an article on JavaScript Namespacing and another one called "An Important Pair of Parens," so I know some about what's going on here.
But I've never seen this particular syntax before. What is that undefined doing there? And why does window need to be passed and then appear at the end again?
The undefined is a normal variable and can be changed simply with undefined = "new value";. So jQuery creates a local "undefined" variable that is REALLY undefined.
The window variable is made local for performance reasons. Because when JavaScript looks up a variable, it first goes through the local variables until it finds the variable name. When it's not found, JavaScript goes through the next scope etc. until it filters through the global variables. So if the window variable is made local, JavaScript can look it up quicker.
Further information: Speed Up Your JavaScript - Nicholas C. Zakas
Undefined
By declaring undefined as an argument but never passing a value to it ensures that it is always undefined, as it is simply a variable in the global scope that can be overwritten. This makes a === undefined a safe alternative to typeof a == 'undefined', which saves a few characters. It also makes the code more minifier-friendly, as undefined can be shortened to u for example, saving a few more characters.
Window
Passing window as an argument keeps a copy in the local scope, which affects performance: http://jsperf.com/short-scope. All accesses to window will now have to travel one level less up the scope chain. As with undefined, a local copy again allows for more aggressive minification.
Sidenote:
Though this may not have been the intention of the jQuery developers, passing in window allows the library to be more easily integrated in server-side Javascript environments, for example node.js - where there is no global window object. In such a situation, only one line needs to be changed to replace the window object with another one. In the case of jQuery, a mock window object can be created and passed in for the purpose of HTML scraping (a library such as jsdom can do this).
Others have explained undefined. undefined is like a global variable that can be redefined to any value. This technique is to prevent all undefined checks from breaking if someone wrote say, undefined = 10 somewhere. An argument that is never passed is guaranteed to be real undefined irrespective of the value of the variable undefined.
The reason to pass window can be illustrated with the following example.
(function() {
console.log(window);
...
...
...
var window = 10;
})();
What does the console log? The value of window object right? Wrong! 10? Wrong! It logs undefined. Javascript interpreter (or JIT compiler) rewrites it this way -
(function() {
var window; //and every other var in this function
console.log(window);
...
...
...
window = 10;
})();
However, if you get the window variable as an argument, there is no var and hence no surprises.
I don't know if jQuery is doing it, but if you are redefining window local variable anywhere in your function for whatever reason, it is a good idea to borrow it from global scope.
window is passed in like that just in case someone decides to redefine the window object in IE, I assume the same for undefined, in case it's re-assigned in some way later.
The top window in that script is just naming the argument "window", an argument that's more local that the global window reference and it what the code inside this closure will use. The window at the end is actually specifying what to pass for the first argument, in this case the current meaning of window...the hope is you haven't screwed up window before that happens.
This may be easier to think of by showing the most typical case used in jQuery, plugin .noConflict() handling, so for the majority of code you can still use $, even if it means something other than jQuery outside this scope:
(function($) {
//inside here, $ == jQuery, it was passed as the first argument
})(jQuery);
Tested with 1000000 iterations. This kind of localization had no effect in performance. Not even a single millisecond in 1000000 iterations. This is simply useless.
This is probably pretty easy, yet I am confused, so maybe I might still learn something more today. I am trying to do the following:
var myObj = {};
myObj.src = {}
myObj.src.A = ['1.png','2.png','3.png'];
myObj.A = new Image();
myObj.A.src = this.src.A[0];
This will result in an Uncaught TypeError: Cannot read property 'A' of undefined error.
When I use myObj.src.A[0] instead of this it is working fine.
What would be the correct way to use this in this context?
this refers to the object context in which the code is executing. So if an object has a method aMethod, then inside aMethod this references the object that owns it.
I'm assuming your code there is running in the global namespace, so this is undefined. Really you just want myObj.A.src = myObj.src.a[0];.
http://www.quirksmode.org/js/this.html
The this keyword is always different depending on the scope involved. In the code snippet you've posted above, assuming that you're just putting this in the document somewhere in the head, this refers to the page itself. So, it's fairly obvious at that point that this.src.A will be undefined. If you were to apply an event to it with a delegate such as:
myObj.click = function() {
alert(this.src.A[0]);
}
The this keyword receives a new scope belonging to the owner of the delegate (in this case myObj). this is very easy to track so long as your clearly define your scopes and your scope boundaries.
this does not refer to var myObj in the case of your code. It is likely that if you are not inside the scope of a function or an objects method then this is referring to the DOM window which has no attribute src.A
this in JavaScript depends heavily on the context in which a function is called. If your code is (as it looks to be above) just hanging out in a script tag in the page, then this is going to be the "global" context -- which in the browser is the window object.
Generally, this refers to the object/scope a function belongs to, but there's a number of special (and useful) cases that happen because functions are first class values that can be assigned to different objects and invoked in various contexts.
Some lengthy elaboration others have written might be helpful:
https://stackoverflow.com/a/3320706/87170
http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/
http://net.tutsplus.com/tutorials/javascript-ajax/fully-understanding-the-this-keyword/
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special_Operators/this_Operator
It can seem a little tricky at the start, particularly if you're used to languages in which this is always one thing, but after you learn a few rules it becomes fairly straightforward and actually very useful.
myObj.src.A[0] would be correct in this context because this references its immediate parent.
Every property of the window object is a global variable. This means you can do something like this:
window.foo = 42;
alert(foo); //alerts 42
var bar = 3;
alert(window["bar"]); //alerts 3
Because of this, I've always wondered what the purpose was of referencing window in code like this
if(window.prompt("Enter Password") === "secret") {
window.location.hash = "authorized";
window.open("secretPage.html");
}
when you could omit window and have code that does exactly the same thing:
if(prompt("Enter Password") === "secret") {
location.hash = "authorized";
open("secretPage.html");
}
The use also seems inconsistent; I almost never see window.alert but I'll frequently see window.location.
Do people just like referencing window to make their code more verbose? Is there some good reason for doing this that I don't know about?
One situation in which it helps to be explicit is that it will be immediately clear inside a function that you intend to modify a global variable. For example:
function blah() {
// a bunch of code preceding...
test = "aha!";
}
Did someone forget to declare test with var? Or is this intentional modification of a global? Compare:
function blah() {
// a bunch of code preceding...
window.test = "aha!";
}
Now it's immediately clear what is intended. Of course, you know, globals should be avoided in the first place, but you get my point.
window is implicit, but it's good code practice to avoid ambiguity where possible.
I think it's generally used to avoid potential clashes with other variables in an enclosing closure. Also, style checkers like jslint will raise errors if you access global properties without an explicit object (except for well-known properties like window itself.)
That said, in a browser, when you get into multiple windows, e.g., with iframes, etc., you may need to explicitly pass around a reference to the window object. (And if you really care about the details, the window object, or at least references to it, are very special and can't even be described in standard javascript.)