Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing window and undefined to an immediately invoked anonymous function. Why? [duplicate]

Possible Duplicate:
why do we need to pass in window and undefined into this jquery plugin?

I've seen jQuery source code does this:


(function(window, undefined){

...

}(window))

I get why is it useful to include undefined, if someone where to change "undefined" before. But window cant be changed. For all I know, it doesnt even need to be used, right? How could this be useful?

like image 467
Enrique Moreno Tent Avatar asked Nov 26 '11 01:11

Enrique Moreno Tent


People also ask

Can you assign an anonymous function to a variable and pass it as an argument to another function?

They're called anonymous functions because they aren't given a name in the same way as normal functions. Because functions are first-class objects, we can pass a function as an argument in another function and later execute that passed-in function or even return it to be executed later.

What is the point of anonymous functions?

The advantage of an anonymous function is that it does not have to be stored in a separate file. This can greatly simplify programs, as often calculations are very simple and the use of anonymous functions reduces the number of code files necessary for a program.

What is function () )() in JavaScript?

It's an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it's created. It has nothing to do with any event-handler for any events (such as document. onload ). Consider the part within the first pair of parentheses: (function(){})(); ....it is a regular function expression.

Can anonymous function be passed as a parameter?

An anonymous function is a function with no name which can be used once they're created. The anonymous function can be used in passing as a parameter to another function or in the immediate execution of a function.


1 Answers

Micro optimisation.

Having window as a local variable is marginally faster than a global variable.

It also minifies better. We can now minify the function parameter to w and use w.setTimeout etc instead of window.setTimeout.

Fewer bytes = better

like image 180
Raynos Avatar answered Oct 27 '22 00:10

Raynos