2010-02-10 4 views

risposta

6

Utilizzare this.init(), ma questo non è l'unico problema. Non chiamare nuove sulle funzioni interne.

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

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

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

// etc etc 
+0

Ma con questo, non posso chiamare ' Test.init() 'di un'altra classe. Come faccio a fare in modo che 'Test' sia un singleton ma è comunque possibile chiamare' init() 'in questo modo? – Chetan

+0

@Chetan: vedere le modifiche. –

+0

Funziona bene per me, Firebug non si lamenta. Hai rimosso il "nuovo" dalle dichiarazioni di funzione all'interno del test? –

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

A meno che non mi manca qualcosa qui, è possibile eliminare il "nuovo" dal codice.

+0

Che va benissimo ... No? –

2

Prova questo,

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 

Grazie.

3

Invece, provare a scrivere in questo modo:

function test() { 
    var self = this; 
    this.run = function() { 
     console.log(self.message); 
     console.log("Don't worry about init()... just do stuff"); 
    }; 

    // Initialize the object here 
    (function(){ 
     self.message = "Yay, initialized!" 
    }()); 
} 

var t = new test(); 
// Already initialized object, ready for your use. 
t.run() 
+0

Ha funzionato per me, usando Node.js –