How to call a function during object construction in Javascript?

Parminder picture Parminder · Jan 25, 2011 · Viewed 10.5k times · Source

I want to create an object and run two of its methods on object creation. So if my object is

function newObj(){
this.v1 = 10;
this.v2 = 20;
this.func1 = function(){ ....};
this.func2 = function(){...};
}

and the call to the object is

var temp = new newObj();

I want to run func1() and func2() without calling them explicity on temp variable, like temp.func1(). I want them to be called when I create the new Object variable. I tried putting this.func1() inside the newObj declaration but it doesn't seem to work.

Answer

Zango picture Zango · Jan 25, 2011

Add method invocation statements in constructor:

function newObj(){
this.v1 = 10;
this.v2 = 20;
this.func1 = function(){ ....};
this.func2 = function(){...};
this.func1();
this.func2();
}

I think it is solution of your needs.