A function is a very important language element in JavaScript and provides a function keyword and a built-in object function. The following describes its possible usage and the relationship between them.
Method 1: VaR Foo01 = Function () // Or fun01 =Function()
{
VaR Temp = 100 ;
This . Temp = 200 ;
Return Temp + This . Temp;
}
Alert ( Typeof (Foo01 ));
Alert (foo01 ());
Running result:Function
300
The most common function usage method is to define a JavaScript function. The two statements have the same running effect, but the only one is that the latter one has a higher initialization priority. In the variable scope of the expanded number, this refers to the owner of foo01, that is, the window object.
Method 2: VaR Foo02 = New Function ()
{
VaR Temp = 100 ;
This . Temp = 200 ;
Return Temp + This . Temp;
}
Alert ( Typeof (Foo02 ));
Alert (foo02.constructor ());
Running result:
Object
300
This is a usage of puzzle functions, as if to define a function. But this is actually a User-Defined Object in Javascript, but here it is an anonymous class. This usage has nothing to do with the use of the function itself, and a variable scope will be built in the large expansion number. This refers to the scope itself.
Method 3:
VaR Foo3 = New Function (' VaR Temp = 100 ; This . Temp = 200 ; Return Temp + This . Temp ;');
Alert ( Typeof (Foo3 ));
Alert (foo3 ());
Running result:
Function
300
Build a function using the built-in function object. This is the same as the first method in method 1 in terms of effect and initialization priority, that is, the function body is given as a string.
Method 4: VaR Foo4 = Function (' VaR Temp = 100 ; This . Temp = 200 ; Return Temp + This . Temp ;');
Alert ( Typeof (Foo4 ));
Alert (foo4 ());
Running result:Function
300
This method is not often used. The effect and method are similar, but it is unclear whether new is not used to generate any side effects. This also reflects one of the biggest features of javascript: flexibility! Save.
For more information about the Function initialization priority, see :"Differences between the two implementation methods of JS class definition prototype.