The Function class in JavaScript
Posted: | Categories: JavaScript, Programming | Tags: Function
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!");
For those who didn’t figure it out, the syntax of the Function
class is the following: