Function class
Definition
The Function class can represent any function defined by the developer. The syntax of using the Function class to directly create a function is as follows:
var function_name=new Function(agrument1,agrument2,. ..,argumentN,function_body);
Each argument is a parameter, and the last parameter is the function body (the code to be executed).
Example:
function sayHi(sName ,sMessage){
alert("Hello " sName "," sMessage);
}
It can also be defined as follows:
var sayHi=new Function("sName" ,"sMessage","alert("Hello" sName "," sMessage);");
Note: Although functions can be created using the Function constructor, it is best not to use it because it is easier to define functions than in the traditional way. Much slower. However, all functions should be considered instances of the Function class.
Properties and methods
Because functions are reference types, they also have properties and methods. The attribute length defined by ECMAScript declares the number of parameters expected by the function, for example:
function doAdd(iNum){
alert(iNum 10);
}
function sayHi (){
alert("Hi");
}
alert(doAdd.length);//outpus 1
alert(sayHi.length);//outpus 0
Function objects also have standard valueOf() and toString() methods shared with all objects. Both methods return the source code of the function, which is especially useful when debugging.
For example:
function doAdd(iNum){
alert(iNum 10);
}
alert(doAdd.toString());
This code outputs the text of the doAdd() function.
Closure
Definition
The so-called closure refers to the lexical representation of a function that includes variables that do not need to be calculated. In other words, the function can use variables defined outside the function. Using global variables in ECMAScript is a simple example of closures.
Example:
var sMessage="Hello World" ;
function sayHelloWold(){
alert(sMessage);
}
sayHelloWorld();
Defining a function within another function causes the closure to become More complex, such as:
var iBaseNum=10;
function addNumbers(iNum1,iNum2){
function doAddtion(){
return iNum1 iNum2 iBaseNum;
}
return doAddtion();
}
This function addNumbers() includes the function doAddtion() (closure). The inner function is a closure because it will obtain the parameters iNum1 and iNum2 of the outer function and the value of the global variable iBaseNum. The last step of addNumbers() calls the internal function, adds the two parameters and the global variable, and returns their sum. The important concept to grasp here is that the doAddtion() function does not accept parameters at all, it uses the ones obtained from the execution environment.
As you can see, closures are a very powerful and versatile part of ECMAScript and can be used to perform complex calculations. As with any advanced function, be careful when using closures as they can get very complex.
Sample code in this article