Function is a very important language element in JavaScript, and it provides a function keyword and a built-in object Function. The following is 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 results:
function
300 The most common way to use function is to define a JavaScript function. The two writing methods have exactly the same operating effects, but the only difference is that the latter writing method has a higher initialization priority. In the variable scope within the large expansion sign, this refers to the owner of foo01, which is the window object.
Method two:
var foo02 = new function()
{
var temp = 100;
this.temp = 200;
return temp this.temp;
}
alert(typeof(foo02 ); But actually this is a user-defined object in JavaScript, but here it is an anonymous class. This usage has basically nothing to do with the use of the function itself. A variable scope will be constructed in the large expansion sign, and this refers to the scope itself.
Method 3:
Copy code
alert(typeof(foo3));
alert(foo3());
Run result: function
300 Use the system’s built-in function object to construct a function. This is exactly the same as the first method in method 1 in terms of effect and initialization priority, that is, the function body is given in the form of a string .
Method four:
Copy code
alert(typeof(foo4));
alert(foo4());
Run result:
function
300 This method is not commonly used. The effect is the same as method three. However, it is not clear whether there are any side effects of not using new to generate it. This also reflects one of the biggest disadvantages of JavaScript. Features: Flexible! Save what you can.
Regarding the issue of function initialization priority, you can refer to the reply: "The difference between the two implementations of JS class definition prototype method".