views:

169

answers:

3

I have this:

var Test = new function() {  
    this.init = new function() {  
        alert("hello");  
    }
    this.run = new function() {  
        // call init here  
    }  
}

I want to call init within run. How do I do this?

+2  A: 

Use this.init(), but that is not the only problem. Don't call new on your internal functions.

var Test = new function() {
    this.init = function() {
        alert("hello");
    };

    this.run = function() {
        // call init here
        this.init();
    };
}

Test.init();
Test.run();

// etc etc
Jeff B
But with this, I can't call `Test.init()` from another class. How do I make it so that `Test` is a singleton but still be able to call `init()` this way?
Chetan
@Chetan: see edits.
Jeff B
Works fine for me, firebug does not complain. Did you remove the "new" from the function declarations inside of test?
Jeff B
You forgot to drop the new from the top function... The constructor
Mike Sherov
+1  A: 
var Test = function() {
this.init = function() {
 alert("hello");
} 
this.run = function() {
 this.init();
}
}

unless I'm missing something here? drop the "new" from your code.

Mike Sherov
Which is perfectly fine... No?
Mike Sherov
A: 

Try this,

 var Test =  function() { 
    this.init = function() { 
     alert("hello"); 
    }  
    this.run = function() { 
     // call init here 
     this.init(); 
    } 
} 

//creating a new instance of Test
var jj= new Test();
jj.run(); //will give an alert in your screen

Thanks.

Hoque