1. function declaration Type
Copy Code code as follows:
In JS, functions are also objects, function objects are connected to Function.prototype (Function.prototype connected to Object.prototype)
2, function literal type
Copy Code code as follows:
var foo = function foo () {
Code
}
Object has a hidden connection to the prototype object. Object literals are connected to Object.prototype. foo.__proto__ = = Function.prototype
3, using the new constructor to generate
New Function ([arg1[, arg2[, ... argn]],] functionbody);
New functions are generated for each execution
There are a lot of information on the web about these three modes, the first 2 are almost the same, based on the same lexical scope.
Lexical scopes: The scope of a variable is determined when it is defined, not when it is executed, that is, the lexical scope depends on the source code, which can be determined by static analysis, so the lexical scope is also called a static scope. With and Eval excepted, so can only say JS scope mechanism is very close to the lexical scope (lexical scope).
Suddenly feeling a bit off the point, this article is actually the difference between eval and new function, the following return to the topic:
It's been said before that the new function is almost equal to eval, and today I looked it up, and it was a different thing, and the person who said it was too irresponsible. As for the Eval and new function, the results are consistent and will tell you not to use them. So the conclusion is "have to" only use.
Eval () evaluates a string as a JavaScript expression within the current execution scope and can access local variables.
The new Function () parses the JavaScript code stored in a string into a Function object, which can then to be called. It cannot access local variables because the code runs in a separate scope.
As you can see from the above 2 points, the scope of eval is the current scope, and the new function is dynamically generated, and its scope is always window. Also, eval can read local variables, and the new function cannot.
Copy Code code as follows:
function Test () {
var a = 11;
Eval (' (a = 22) '); If the new Function (' return (a = 22); ') (); The value of a is not overwritten.
alert (a); Alerts 22
}
So the general eval is only for converting JSON objects, and the new function has a special purpose, but it's better to use it less clearly.
More information: The Evil eval and new Function
Make a backup here:
Code:
Copy Code code as follows:
Friendly reminder: For your fingers to be safe, please run it under Chrome
' Alert (' Hello ') '. Replace (/.+/, eval);
' Alert (' Hello ') '. Replace (/.+/, function (m) {new function (m) ();});
var i = 0; Eval (new Array. Join (' alert (++i); ');
var i = 0; New Function (New Array (' Alert (++i); ') ();