This question already has answers here:
How does this JavaScript/jQuery syntax work: (function( window, undefined ) { })(window)?
(5 answers)
Closed 8 years ago.
In some Javascript code which uses immediate function, it has argument window or document like the following:
(function (window, document) {
...
})(window, document);
However, window and document are global objects and can be directly accessed as follow:
(function () {
var userAgent = window.navigator.userAgent;
...
var el = document.getElementById(...)
...
})();
What are the differences between the above two codes. Which is better way and why?
Two reasons I can think of:
1) Local variables are the first in the scope chain, so their access is faster than globals (with faster I mean insignificantly faster).
2) Inside the function, window and document are local variables, so their names can be minimified:
(function (w, d) {
//var userAgent = w.navigator.userAgent;
)(window, document);
What are the differences between the above two codes. Which is better way and why?
In all practicality and usage in browsers only, there's no appreciable difference.
That said, there's a very slight performance increase that comes from referencing local variables instead of globals.
Also, it allows the flexibility of swapping out the real window by a mock version; this could be useful during testing and in certain environments where some of the objects are not available and must be replaced.
Btw, there's another kind of argument you could pass, which is undefined; it goes like this:
(function(undefined) {
// your code
}());
You don't actually pass anything to the outer function and by doing so you make sure that undefined has not been tampered with; pedantic people like myself would just void 0 for that purpose though :)
The difference is polymorphism: in the first case, you could pass the function any pair of objects that behave as the window and the document objects (at least for the methods your function calls), and the function will work too with them.
In practice, with this two objects in particular, it's more error prone that any benefit - everyone expects window and document to be the window and document defined by Javascript. But in theory, that's the gain.
Related
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 question already has answers here:
What does "this" mean in jQuery? [duplicate]
(6 answers)
Closed 7 years ago.
Reviewing some legacy code and saw it. The function body was done in pure Javascript without using any 3rd party library.
Could anyone shed a light on the use of "this" in (function() { })(this)?
Full codes:
(function() {
var root = this;
var SOMEVAR;
SOMEVAR = root.SOMEVAR = {};
SOMEVAR.windowOffset = 0;
SOMEVAR.defaultBase = 195;
SOMEVAR.resizeIFrame = function(){
// some codes
};
SOMEVAR.resetIFrameSize = function(height) {
// some codes
}
window.SOMEVAR = SOMEVAR;
})(this);
I actually read all "this" related usages before I asked the question. I just couldn't find this usage fits in those I read. And somehow, I don't think the "this" here is not even necessary because all the codes want is to create the "SOMEVAR" and bind it to "window". Am I correct?
Thanks
This is a somewhat weird example of an Immediately-Invoked Function Expression (IIFE). The first part:
(function(){})
simply defines a function (the outer parentheses are unnecessary). This function is then called, passing this as an argument. Usually one would actually declare a parameter and then do something to the parameter inside the function:
(function(context) {
// do something to or with context
})(this);
What object is actually referenced by this depends on where this code is executing and whether strict mode is in effect. See the docs for this for more information.
You're defining an anonymous function and then immediately invoking it with the this parameter.
If you're just looking to understand the meaning of this, then refer to this other question.
Ah, what is this. The oldest question in the javascript book. Generally speaking, this refers to the context that the current code is being executed in. If you have "top level" code being run straight in a script tag, it refers to window. In a click event? The current element. In a constructor? The object that will be constructed. You can even make it whatever you want with call and apply.
If you see this construct:
(function(ns) { })(this);
not inside other function then this is a reference of default namespace of script execution. In browsers that default namespace has quite strange name window therefore the following will output true:
(function(ns) {
console.log( ns === window );
})(this);
Such ns (namespace) variable is useful when you need for example check variable existence in namespace. This, for example:
alert(foo);
will rise an error "undefined variable foo", but this:
(function(ns) {
alert(ns.foo);
})(this);
will show alert with the word "undefined".
Another usage is in modules that can work as inside browser as in node.js and the like. Node.js has no notion of window so that construct above is the only reliable way to get reference to default namespace/scope object.
This question already has answers here:
What does "options = options || {}" mean in Javascript? [duplicate]
(5 answers)
Closed 8 years ago.
When should I use such syntax to define a function in JavaScript
myfunc = myfunc ||
function(n){
return this.length;
};
instead of
myfunc =
function(n){
return this.length;
};
In above case this is being checked if myfunc is not defined, then define that as a function.
So when you are not sure that the myfunc is already defined you will check if it's undefined define a function.
Basically, when you don't want to override the previous declaration of the function.
For instance, imagine that you have a function A(), which performs a set of actions and it's declared in another library. Maybe you need to use only a small part of it, so you can use the previous syntax to redeclare the function.
It's not a consistent way to program, and it will make the code hard to debug, but it's doable.
As other posters have pointed out, you can use the first expression when you want to define a function which may or may not have been previously defined. It's not a good way to do it though, because the construct does not tell you whether the tested object is a function, and if it is, whether it is the one you're expecting (it could be the result of collapsing libraries).
More generally, the whole redefinition approach should be limited to framework authors, and even with that I'd be quite suspicious of any redefinition, because that would indicate that someone, somewhere, has allowed for either namespace pollution or sloppy dependency management.
I have myself redefined existing functions in some of my past scripts, but these occurrences were all about optimization in a controlled environment, when the initial function determines an execution branch for the current user agent, and redefines itself so that further calls avoid any redundant initialization code.
I've seen this syntax for creating an anonymous constructor function in JavaScript:
var Application = Application || {};
!function(window, Application) {
Application.property = {/*...*/}
Application.method = function(){/*...*/}
}(window, Application);
I want to understand what the following parts here:
What is the advantage of using first line (i.e. var o = o || {};) vs just stating var o = (function(){})();?
Why ! is used in front of function?
Why would I pass window or Application as parameters when they are global object?
Is this the most convenient way for anonymous constructor function and how is this better than:
4a)
var Application = {
property: {},
method: function(){}
}
or 4b)
var Application = (function() {
var method = function(){/*...*/}
return {method:method};
}());
The first line is to ensure that Application always exists, and is generally used in cases where it's expected that Application already should exist, and the function just augments the existing object. If it doesn't exist, this makes sure that we don't get an error for accessing properties of undefined. Your examples are only equivalent in the case where Application does not yet exist. In all other cases, your code will obliterate the existing Application, which is almost certainly not the intent.
The comment from Vatev explains what the ! does. It's another syntax for making the function in question become a self executing anonymous function. (Incidentally, it also takes the return value of the function - which is currently undefined, and flips its truthyness, so it evaluates as true. Since the result isn't stored in any variable, though, that's clearly not the purpose.)
Finally, why pass window and Application into the function and use it there? This is a safety feature, in case other code changes window or Application later on. It guarantees that within the anonymous function, window and Application are exactly what you expect it to be. In the shorthand example you gave, this may appear to not matter - after all, why protect these variables if you're using them immediately and not storing them? In many cases, you return something from this function, and then window and Application would be stored in the closure, so you'd retain the variables. It makes it safe from people who later on decide to say Application = {...}.
I don't know all of the answers but I'll try to answer what I can.
Using var Application = Application || {}; simply means that you are dealing with scope. If the "Application" variable has already be defined, it will just mean that it inherits and is now available in the current scope. If not, the "||" part (means OR) means that it will be created as an empty object. You are dealing with creating an object and then acting on it, not just having the result given back raw. That's why you shouldn't use "o = (function() {...});". "o" would then be the result of the function and not the object.
The use of "!function" causes it to be treated as an expression, but this can be tricky because you may have to think in opposites. E.g. !null means you are checking that it isn't null, not that you are checking for it to be null.
Passing in the window and Application objects deal with scoping, again. It is explicitly passing them into the function, then returning them at the end. Think of this as putting clothes in the washing machine. You put them in, stuff can happen, then you get them back out. It's a really crude idea and isn't the best example, but it's how I thought of it a while back. You put clothes in, call then rinse function, then soap function, then rinse again, then spin to drain water.
Hopefully someone else can answer that, I'm not sure what the differences are.
Since two answers so far neglected these two details: A pattern used by libraries like jQuery is using the following two parameters:
(function (window, undefined) {
window.myPlugin = ...;
})(window);
There are two things going on here:
undefined is specified as a parameter, but not passed in. This way, undefined is guaranteed to have th expected value within the inner scope. This is only necessary for older browsers which allowed overwriting undefined (though it has always been considered bad practice to do so – it's just what libraries like jQuery do to avoid other code interfering with their code).
Aliasing a global object like window within the scope allows the code to be minified more (also works for undefined). Obviously, the more references you have to the aliased object(s), the more you will save:
.
(function(w,u){w.myPlugin=...;w.somethingElse=...;if(whatever===u){return;}})(window);
compared to
(function(){window.myPlugin=...;window.somethingElse=...;if(whatever===undefined){return;}})();
You won't save much with window since typically you don't wanna clutter the global object up anyway. But aliasing undefined can save you quite some space.
This question already has answers here:
How to test for equality of functions in Javascript [duplicate]
(7 answers)
Closed 1 year ago.
Is it possible to detect duplicate functions in Javascript (which may be written by accident in some cases)? In Google Chrome,
printLah(); //this prints "Haha" for some reason, without even printing an error message in the Javascript console!
function printLah(){
alert("Hahah!");
}
function printLah(){
alert("Haha");
}
Here it is on JSfiddle.
The short answer is, no it's not.
This is how javascript works. A function name is just a variable that is assigned a function. For example:
function foo () {
alert('foo!');
}
foo = 1;
foo();
The code above will generate an error because a number is not a function! There is no difference between function names and variable names. In fact, an alternative way to define functions looks exactly like how you'd define variables:
var foo = function () {
alert('foo!');
}
It's because of this functions-as-first-class-objects behavior that javascript cannot prevent re-assignment otherwise you cannot re-assign variables (pure functional languages on the other hand have no problems with disallowing variable re-assignments).
Work-arounds and best practice:
This is the reason people keep saying that you shouldn't define too many globals in javascript. That includes functions. Otherwise it may clash by accident with someone else's code.
There are two powerful features in javascript that can mitigate this problem: objects and closures.
Because javascript supports objects you should use object oriented programming to limit the number of globals in your program. Unlike traditional OOP, javascript works better when using objects as collections or namespaces. This is because javascript doesn't have file scope and everything is global.
This doesn't mean you shouldn't create smaller objects that encapsulate smaller problems like you do with traditional OOP. It just means that you should, if you can, contain all your objects within a single parent object. And I don't mean inheritance here, I mean in a has-a relationship. Look at popular libraries like jQuery and Raphael for examples of this. They export only one object to the global scope to avoid clashing with other people's code.
But, again, this doesn't really protect people from re-assigning your objects (because they're variables after all). For example, you can easily break jQuery by doing this at the top of your HTML file before other bits of javascript have the chance to run:
jQuery = null;
The way to protect your code from being tampered with is to use a closure. Third party code has no access to any code you run from inside your closure. As long as you avoid globals that is.
Just to follow on from slebetman's answer, you can use the following to check for existence before declaring a variable or function.
if (typeof(functionName) == 'undefined') {
functionName = function() {
// add code here
}
}
Once again, the reason you would do this check is because you want/need to put something in the global scope, even though it is often not needed. Not using a var puts it implicitly into the global scope.
Try this.It work for me !!!
$(document).ready(function () {
var all_functions = [];
var duplicate_functions = [];
var reportRecipientsDuplicate = [];
for (var i in window) {
if ((typeof window[i]).toString() == "function") {
if (window[i].name) {
all_functions.push(window[i].name);
}
}
}
var all_functions1 = all_functions.sort();
for (var i = 0; i < all_functions1.length - 1; i++) {
if (all_functions1[i + 1] == all_functions1[i]) {
duplicate_functions.push(all_functions1[i]);
}
}
console.log("Duplicate functions on page");
console.log(duplicate_functions);
});