DEV Community

Janaka Dissanayake
Janaka Dissanayake

Posted on

What is Constructor in Javascript

In JS world there is a term called the constructor, people like me who have C#/Java background has a lot of confusion when it implements this in a real application. So I have done a small research and came with the following understanding

Alt text of image

function jsObject(name){ this.name = name };
// call function
let obj = jsObject("myName");
obj.name;

// VM603:1 Uncaught TypeError: Cannot read property 'name' of undefined
// at <anonymous>:1:3

Les't fix this

function jsObject(name){ 
   var myObj = {};
   myObj.name = name;
   return myObj;
};

// call function
let obj = jsObject("myName");
obj.name;

// --> myname

works fine, so that is, NO javascript give some cool feature


// call function
let obj =  new jsObject("myName");
obj.name;
// --> myname

what happened, yes javascript gives some cool stuff to developers.it adds following line at runtime when it is called with new.


function jsObject(name){ 
   // var this = {};-> add at run time 
   this.name = name;
   // return this; -> add at run time 
};

Now I know constructor function, but feel free to add your comments

Top comments (0)