tags:

views:

41

answers:

3

I have a class similar to the one below. How do I call my init method when the object is created? I don't want to have to create an instance of my object then call initialize like I do below.

var myObj = new myClass(2, true);
myObj.init();

function myClass(v1, v2) 
{
    // public vars
    this.var1 = v1;

    // private vars
    var2 = v2;

    // pub methods
    this.init = function() {
        // do some stuff        
    };

    // private methods
    someMethod = function() {
        // do some private stuff
    };
}
+2  A: 

NB. Constructor function names should start with a capital letter to distinguish them from ordinary functions, e.g. MyClass instead of myClass.

Either you can call init from your constructor function:

var myObj = new MyClass(2, true);

function MyClass(v1, v2) 
{
    // ...

    // pub methods
    this.init = function() {
        // do some stuff        
    };

    // ...

    this.init(); // <------------ added this
}

Or more simply you could just copy the body of the init function to the end of the constructor function. No need to actually have an init function at all if it's only called once.

Daniel Earwicker
Thanks. I actually tried calling 'this.init();' before posting, but I was making the call before the function declaration so that is why it would not work. =]
Aros
A: 

Just add

this.init();

to your myClass function.

harpo
+1  A: 

See below for one possible answer, and some corrections to your code.

function myClass(v1, v2) 
{
    // public vars
    this.var1 = v1;

    // private vars
    // use var to actually make this private
    var var2 = v2;

    // pub methods
    this.init = function() {
        // do some stuff        
    };

    // private methods
    // this will be private as though it had been declared with var
    function someMethod() {
        // do some private stuff
    };

    //call init
    this.init();
}
echo-flow
Thanks, that was a typo when converting my real class to a simple example for the question.
Aros