has been to function () smattering, today on the use of function () to do a summary
The function is actually a fully functional object, and the function is created directly with Fucntion ().
Syntax rules:
var function name = new function (arg1, arg2, Arg3, ..., ArgN, body);
Explain:
Function constructors All arguments are string types, and body is the body of the generated function.
Example: To find multiple parameters and
var New Function ( ' var = 0,args = Arguments;for (var i = 0; i < args.length; i++) {Total + = args[i];} return total; ' ); var res = fnsum (4,5,6); Alert (res);
View Code
Note: The above code is not allowed to have spaces
To improve the above wording
First notation (Traditional): Splitting a string
var New Function ( ' var = 0, ' + ' args = arguments; ' + ' for (var i = 0; i < args.length; i++) {' + ' total + = args[i]; ' + ' } ' + ' return total; ' ); var res = fnsum (1,2,3,4 ); Alert (res); // Ten
View Code
The second way: absorbing the idea of MVC
<script id= "Engin" >/*var total = 0, args = arguments, Len = args.length; for (var i = 0; i < len; i++) {Total + = args[I]; } return total;*/</script> <script>varGetBody =function(ID) {varScript =document.getElementById (ID); varBODY = Script.innerHTML.replace ('/* ', '). Replace (' * * ', ' '); Script.parentNode.removeChild (script); returnbody; } onload=function () { varFnsum =NewFunction (GetBody (' Engin ' ) ); varres = Fnsum (1, 2, 3 ); Alert (res); //6};
View Code
Both function and eval can implement string execution code in real development, if you consider efficiency you can use eval directly, but considering security it is recommended to use Function
var str = ' {name: ' jim '} 'var o = ' + str'//var o = eval (' (' + str + ') '); In the sentence console.log (o); // Object {name: "Jim"}
Eval (' var a = ten; '); // eval will contaminate global variables var a = 10; // Global Variables
eval()
is a top-level function and is not related to any object.
eval()
The argument is a string. If the string represents an expression,eval () will execute the declaration. Do not call
If you want to construct an arithmetic expression into a string, you can use 3 * x + 2 ", as a variable, by calling
如果参数不是字符串,
eval () 将会将参数原封不动的返回。
in the following example, the string constructor is specified, andeval () returns a String object instead of a string evaluation.
eval()
is a dangerous function that can invoke code just like the power of a caller. If you use a string to runeval () then your code may be affected by malicious parties (hostile people), and by using malicious code on the user's machine, you may lose access to the Web page or extension https://developer.mozilla.org/zh-cn/docs/ Web/javascript/reference/global_objects/eval
About new function use