Most programmers know how to define and use a function in JavaScript. For example, the following function displays an alert containing the string passed in as a parameter:
function displayAlert(sText) {
alert(sText);
}
// Then you call it this way
displayAlert("Hello World!");
How many developers, however, know that JavaScript functions are actually objects? Indeed, you can define the previous
function using the Function class:
var displayAlert = new Function("sText", "alert(sText);");
//...and you call it the same way
displayAlert("Hello World!");
In case it wasn’t clear, the syntax of the Function class is the following:
var functionName = new Function(arg_1, arg_2, ..., arg_n, functionBody);
where arg_i (i = 1,…,n) is the i-th argument and functionBody is (you guessed it) the body of the function.
Although you can define functions using the Function class, it’s best to avoid it because it’s less performant than
the traditional way. Knowing that a function is an object is useful because you can call
the valueOf() and toString() methods shared by all objects on it. However, when called on a function, these two methods
return the source code for the function as a string. You can also access the length property defined in ECMAScript. This property returns the number of arguments as defined in the function. For example:
function displayAlert(sText) {
alert(sText);
}
//display an alert containing the number of arguments (in this case 1)
alert(displayAlert.length);