Home > Web Front-end > JS Tutorial > The difference between function, new function, new Function_javascript skills

The difference between function, new function, new Function_javascript skills

WBOY
Release: 2016-05-16 19:17:49
Original
1091 people have browsed it

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:

Copy code The code is as follows:

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:
Copy code The code is as follows:

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
The code is as follows: var foo3 = new Function ('var temp = 100; this.temp = 200; return temp this.temp;');
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
The code is as follows: var foo4 = Function('var temp = 100; this.temp = 200; return temp this.temp;');
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".
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template