Home > Web Front-end > JS Tutorial > body text

Simple distinction between Function and function in JavaScript

高洛峰
Release: 2016-11-25 11:17:27
Original
1218 people have browsed it

Js code
var a = new Function("document.write(a)");

var b = function(){document.write(b);}

function c(){
document.write(c ; A function that is given a function body.
For the first method, make a summary after searching some information.

Function is Javascript's Unction (note the case), which is derived from it. Function is a reference type (Functions are, of course, reference types.). Personal speculation is similar to the second type of anonymous function reference.
Function instance construction method:
var instanceName = new Function([arg1 [, arg2 [, ...]] ,] body);
The first few items are parameters, and the last is the function body, such as:
Js code
var myAdd = new Function("x", "y", "return x + y");
var sum = myAdd(17, 34);

The value of sum after execution is 51.

The Function() constructor allows us to dynamically create and compile a function without limiting us to the precompiled function body of the function statement. The side effect of this is that every time a function is called, the Function() constructor must compile it. Therefore, we should not call this constructor frequently in loop bodies or in frequently used functions.

Anonymous functions are similar to the Function() constructor in usage; the difference is that the anonymous function is only parsed once when used, while the JavaScript code passed to the Function() constructor as a string is parsed every time the constructor is called. is parsed and compiled once.
Another thing worth noting is that the scope of variables and the Function() constructor variable scope are global.
For example:

Js code

var y="global";

function constructFunction()

{

var y="local";

var fun = new Function("alert(y);");//Do not capture local Scope.
fun();
}
constructFunction();



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