HTML and CSS Reference
In-Depth Information
Both calls shown below are acceptable for the function doSum .
var r1 = doSum(1, 2, 3);
var r2 = doSum(4, 5);
A function that accepts a variable number of arguments is perhaps more clearly defined with no
explicit formal parameters. However, you can also have some parameters declared and still accept and
process any number. At any rate, the arguments array returns the effective list of parameters found in
the call—in the order in which they are listed.
Immediate functions and objects
In JavaScript, an immediate function represents a piece of code that is defined and executed in the
same place. You usually place the definition of a function somewhere (say, in a distinct file) and
invocation goes somewhere else. This approach works well when you expect to use the function
multiple times and from a variety of places. An immediate function is an excellent trick for defining
any work that needs be done only once.
An immediate function has its definition wrapped in parentheses with the list of parameters placed
at the end, as shown below:
var result = (function() {
...
}());
An expression where an immediate function is used, indicates that a value—not the function
itself—is being returned. If the function needs parameters, the previous code can be rewritten as
follows:
var result = (function(x, y, z) {
...
}(1, 2, 3));
// 1,2,3 are actual values for x,y,z
Similarly, you can have immediate objects . An immediate object is a function defined in the same
place where one of its methods is invoked and executed. An immediate object has its literal-based
definition wrapped in parentheses, as below:
({
init: function() {
// perform initialization tasks
},
}).init(...);
Both immediate objects and functions create a scope sandbox that prevents their local variables
from polluting the global namespace.
Search WWH ::




Custom Search