2010-02-10 107 views

Respuesta

6

Use this.init(), pero ese no es el único problema. No llame a nuevo en sus funciones internas.

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

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

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

// etc etc 
+0

Pero con esto, no puedo llamar ' Test.init() 'de otra clase. ¿Cómo lo hago para que 'Test' sea un singleton pero aún así pueda llamar a' init() 'de esta manera? – Chetan

+0

@Chetan: ver las ediciones. –

+0

Funciona bien para mí, Firebug no se queja. ¿Eliminaste el "nuevo" de las declaraciones de funciones dentro de la prueba? –

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

A menos que me falta algo aquí, se puede eliminar la "nueva" de su código.

+0

Lo cual está perfectamente bien ... ¿No? –

2

Prueba de esto,

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 

Gracias.

3

En su lugar, tratar de escribir de esta manera:

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

Me funcionó, usando Node.js –

Cuestiones relacionadas