Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to iterate over public methods inside a function scope?

Tags:

javascript

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/

like image 462
Richard Knop Avatar asked Oct 29 '13 11:10

Richard Knop


4 Answers

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;
like image 113
Boldewyn Avatar answered Oct 02 '22 21:10

Boldewyn


for (var property in new Foo()) {
    console.log(property);
}
like image 25
Barmar Avatar answered Oct 02 '22 21:10

Barmar


Try

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

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

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

Notice the new Foo().

like image 24
Inkbug Avatar answered Oct 02 '22 19:10

Inkbug


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.

like image 33
Sujesh Arukil Avatar answered Oct 02 '22 19:10

Sujesh Arukil