2010-02-10 15 views

Odpowiedz

6

Użyj this.init(), ale to nie jedyny problem. Nie wywołuj nowych funkcji wewnętrznych.

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

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

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

// etc etc 
+0

Ale z tego, nie mogę nazwać ' Test.init() 'z innej klasy. Jak zrobić tak, że 'Test' jest singleton, ale nadal może wywoływać' init() 'w ten sposób? – Chetan

+0

@Chetan: zobacz zmiany. –

+0

Działa dobrze dla mnie, firebug nie narzeka. Czy usunąłeś "nowy" z deklaracji funkcji w teście? –

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

chyba że jestem brakuje czegoś tutaj, można upuścić „nowe” z kodu.

+0

Co jest idealnie w porządku ... Nie? –

2

Spróbuj tego,

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 

Dzięki.

3

Zamiast spróbować napisać to w ten sposób:

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

To działało dla mnie, używając Node.js –

Powiązane problemy