emphaticsunshine emphaticsunshine - 1 month ago 14
Javascript Question

Constructor or init function for an object

I was looking for a constructor or a init function for following situation:

var Abc = function(aProperty,bProperty){
this.aProperty = aProperty;
this.bProperty = bProperty;
};
Abc.prototype.init = function(){
// Perform some operation
};

//Creating a new Abc object using Constructor.

var currentAbc = new Abc(obj,obj);

//currently I write this statement:
currentAbc.init();


Is there a way to call init function when new object is initialized?

Answer

You can just call init() from the constructor function

var Abc = function(aProperty,bProperty){
   this.aProperty = aProperty;
   this.bProperty = bProperty;
   this.init();
}; 

Here is a fiddle demonstrating: http://jsfiddle.net/CHvFk/

Comments