2013-10-29 17 views
5

Considerate questo codice:C'è un modo per iterare su metodi pubblici all'interno di un ambito di funzione?

var Foo = function() { 
    this.bar = []; 

    this.hello = function() { 
     this.name = "world"; 
    }; 
}; 

for (var property in Foo) { 
    alert(111); 
} 

Non fa nulla. C'è un modo per iterare su proprietà e metodi pubblici di Foo? Funzionerebbe se Foo fosse oggetto letterale, come questo:

var Foo = { 
    bar: [], 

    hello: function() { 
     this.name = "world"; 
    } 
}; 

for (var property in Foo) { 
    alert(111); 
} 

Ma preferirei che fosse invece una funzione.

La ragione per cui voglio farlo, voglio estendere da Foo utilizzando il pattern di mixin.

http://jsfiddle.net/ChU2V/

risposta

6

È necessario un'istanza effettiva di Foo per questo al lavoro:

var foo = new Foo(); 
for (var property in foo) { 
    alert(111); 
} 

In caso contrario, le proprietà sono solo "virtuale", nel senso, che non è mai raggiunto il codice del programma.

Oltre a questo, è possibile definire le proprietà sul prototipo:

var Foo = function() {}; 
Foo.prototype = { 
    bar: [], 

    hello: function() { 
     this.name = "world"; 
    } 
}; 

e poi un ciclo su Foo.prototype.

Infine, essendo un linguaggio dinamico, JS permette anche di andare completamente pazzo, se è necessario:

var possible_props = Foo.toString().match(/\bthis\.\([a-zA-Z0-9_]+)\s*=/g); 
// will yield an array similar to this: 
// ["this.bar =", "this.hello ="] 

Nota tuttavia, che questo è molto soggetto ad errori e non raccomandato. Ad esempio, non rileva casi come questo:

var that = this; 
that.baz = null; 
2

Prova

var Foo = function() { 
    this.bar = []; 

    this.hello = function() { 
     this.name = "world"; 
    }; 
}; 

for (var property in new Foo()) { 
    alert(111); 
} 

Avviso del new Foo().

4
for (var property in new Foo()) { 
    console.log(property); 
} 
1

Fiddle aggiornato.

http://jsfiddle.net/sujesharukil/ChU2V/2/

var fooInstance = new Foo(); 
for(var property in fooInstance){} 

È necessario creare un'istanza di Foo al fine di ottenere le proprietà fuori di esso.

Problemi correlati