Consider this code:
var Foo = function () {
this.bar = [];
this.hello = function () {
this.name = "world";
};
};
for (var property in Foo) {
alert(111);
}
It does nothing. Is there a way I can iterate over properties and public methods of Foo? It would work if Foo was object literal, like this:
var Foo = {
bar: [],
hello: function () {
this.name = "world";
}
};
for (var property in Foo) {
alert(111);
}
But I would prefer for it to be a function instead.
The reason I want to do this, I want to extend from Foo using mixin pattern.
http://jsfiddle.net/ChU2V/
You need an actual instance of Foo
for this to work:
var foo = new Foo();
for (var property in foo) {
alert(111);
}
Otherwise, the properties are just "virtual" in the sense, that it's never reached program code.
Other than that, you can define the properties on the prototype:
var Foo = function() {};
Foo.prototype = {
bar: [],
hello: function () {
this.name = "world";
}
};
and then loop over Foo.prototype
.
Finally, being a dynamic language, JS also allows you to go completely crazy, if you must:
var possible_props = Foo.toString().match(/\bthis\.\([a-zA-Z0-9_]+)\s*=/g);
// will yield an array similar to this:
// ["this.bar =", "this.hello ="]
Note however, that this is very error-prone and not recommended. For example, it doesn't catch cases like this:
var that = this;
that.baz = null;
for (var property in new Foo()) {
console.log(property);
}
Try
var Foo = function () {
this.bar = [];
this.hello = function () {
this.name = "world";
};
};
for (var property in new Foo() ) {
alert(111);
}
Notice the new Foo()
.
Fiddle updated.
http://jsfiddle.net/sujesharukil/ChU2V/2/
var fooInstance = new Foo();
for(var property in fooInstance){}
You have to create an instance of Foo in order to get the properties off of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With