Functions keyword (function) statement:
function Fnmethodname (x) {alert (x);}
2. Functions literal (function literals):
var fnmethodname = function (x) {alert (x);}
3. Function () constructor:
var fnmethodname = new Function (' x ', ' Alert (x); ')
The above three methods define the same method function Fnmethodname, the 1th is the most commonly used method, the latter two are to copy a function to the variable fnmethodname, and this function is not a name, that is, anonymous function. In fact, quite a few languages have anonymous functions.
1. (function () {alert ("Hello");}) ()
2, nameless function
Nameless function, in which one effect may be to generate a reference to a new function object, primarily for definition.
Another use is for JS in some of the parameters can not contain the callback function.
The obvious example is setinterval, which I think is a function of a lot of people's headaches, especially when you want to add parameters to the callback function.
And the most troubling thing is that DHTML is not the standard set by the Web, so different browsers give the SetInterval parameter table is not the same ...
For the two browsers I tested (ie kernel, webkit kernel)
Ie:setinvterval (function, Msecond [, Lang]);
Chrome:setinterval (function, Msecond [, pram1, Pram2, ...]);
In other words, the chrome inside is allowed to add parameters to the function, the parameter table on the last side. However, the last parameter of IE is to indicate the type of scripting language used, because IE also supports VBS and other scripting languages except JS.
In order to solve the compatibility, had to use the nameless function ...
[Code]
function test (YOURARG)
{
var arg = Yourarg;
SetInterval (function () {Callback (ARG)}, time);
}
Code patterns for anonymous functions
Yesterday Hedger Wang introduced several code patterns for anonymous functions in his blog:
Error mode: It does not work, the browser will report syntax errors.
function () {alert (1);} ();
1. Function literal: Declare a Function object first, and then execute it.
(function () {alert (1);}) ( );
2. Precedence expression: Because the JavaScript execution expression is from inside the parentheses to the outside, the declared function can be enforced with parentheses.
(function () {alert (2);} ( ) );
3. Void operator: Use the void operator to perform a single operand that is not surrounded by parentheses.
void function () {alert (3);} ()
These three ways are equivalent, Hedger Wang for personal reasons prefer the 3rd kind, and in the actual application I see and use is the 1th kind