JavaScript Constructor Function

Although I’ve been using JavaScript at work to create some prototype applications, I haven’t noticed or used a feature called ‘Function Constructor’. While watching this Udacity course during my weekend, the instructor introduced what it is and I felt that I should record it here for the future use.

Function() constructor is explained as below according to this webpage:

The Function constructor creates a new Function object. Calling the constructor directly can create functions dynamically, but suffers from security and performance issues similar to eval.

So it creates the Function object, just like what classes do in general OOP languages. In JavaScript, the constructors like Function(), Object(), and Array() are not recommended to use because it has no benefits against the object literals like function(), object() and array() in terms of performance. The object defined by constructor gets parsed when it is called, while the object defined with the later one gets parsed with the rest of the code (ref). So what benefit does this constructor have for us? Well, it can create functions during the runtime! What does it mean? Let’s check it out through an example.

A function is normally defined like below without using the constructor in JavaScript:

var exampleFunction = function(a, b){
    return a + b;
}

And above function can be written as below using the constructor:

var exampleFunction = Function('a', 'b', 'return a + b');

The last argument inside the bracket of Function() is the actual function body, and the arguments before that are parameters for the body. This feature can be used as below:

var exampleFunction = function(a){
    return new Function('b', "return '" + a + "'+ b;");
}
console.log(exampleFunction(10)(20));

If you run this code with Node.js, the result is 30. Pretty cool, isn’t it?

So what is the actual benefit of creating a function during the runtime? As this StackOverflow question states, this technique seems to be quite useful if you want to embed certain behaviors of an object in a static data format like JSON and use the behavior later after you call the data.

 

Published by

Hojoong Chung

I learn every day

2 thoughts on “JavaScript Constructor Function”

Leave a comment