Online Forum To Support Coders With Technical Assistance - Read Write Execute

How to declare a function in Javascript using constructor method?

Aman Agrawal
Aman Agrawal
Published on June 19, 2018 · 1 min read

In class-based object-oriented programming, a constructor is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.

Since JavasScript is also an object-oriented programming launguage, there is also constructor methods in JS to create an object.
As we know everyting in JS is an object including fucntion , so can we declare the function as constructor in JS. The answer is yes.

Traditional Syntax


function sum(x, y) {
return x + y;
}

Constructor Syntax

let sum_ctr = new Function("x", "y", "return x + y;");
Was this article helpful?
Aman Agrawal

Aman Agrawal

Author & Senior Engineer at CodeExecute

Writing practical engineering guides, debugging real-world bottlenecks, and creating free tools for developer productivity.

← Previous Article Send email using gmail in CodeIgniter Next Article → Useful shortcodes for woocommerce plugin