Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function during object construction in Javascript?

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.

like image 678
Parminder Avatar asked Jan 25 '11 07:01

Parminder


2 Answers

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.

like image 104
Zango Avatar answered Oct 26 '22 19:10

Zango


Just call it from within the constructor itself it works just fine: http://jsfiddle.net/yahavbr/tTf9d/

The code is:

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

    this.func1();
    this.func2();
}
like image 30
Shadow Wizard Hates Omicron Avatar answered Oct 26 '22 19:10

Shadow Wizard Hates Omicron