Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placing arguments for anonymous functions in JavaScript

When I make an anonymous function in JavaScript like this:

(function(){
/* some code here */
})()

In which object will be this function added, and where will this function live?

Also you can see in the jQuery source code an anonymous function like this:

(function(window, undefined){
    /* some code here */
    })(window)

How do this function's arguments differentiate it from an anonymous, 0-arg function?

like image 872
mechanicious Avatar asked Oct 27 '25 03:10

mechanicious


1 Answers

Functions in JavaScript are values. That is, a function is represented by an object, and like any other object it can be the value of a variable or participate in expressions.

Thus

(function() { ... })

is a value, just like 17 or "hello world" is a value.

When a function (as a value) appears in an expression, and it's followed by (...) with a comma-separated list of expressions between the parentheses, that's a function call.

OK, so:

(function() { ... })()

creates a function (as a value) and then invokes that function with no arguments. The function object, at least as a direct result of that code, is not stored anywhere. It essentially vanishes after the function call completes, and the overall value of that subexpression will be whatever the function returned.

Passing parameters to such a function is no different than passing parameters to any other function. In the specific example you quote, the purpose is to prevent certain kinds of anomalies caused by errant "alien" code. Your example really should read:

(function(window, undefined) {
  // code
})(this);

The symbol this is a reserved word and its value is under complete control of the runtime. (Well, it's value in a local execution context is thusly controlled.) When evaluated in the global scope, the above code ensures that inside the anonymous function, the symbol "window" will be a reference to the global context. That sort of construct is also useful for code that may be used in contexts other than a browser, like Node.js for example, where the global context isn't called "window".

like image 150
Pointy Avatar answered Oct 28 '25 19:10

Pointy