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.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With