10

This question is intentionally phrased like this question.

I don't even know if this is possible, I remember vaguely hearing something about some properties not enumerable in JS.

Anyway, to cut a long story short: I'm developing something on a js framework for which I have no documentation and no easy access to the code, and it would greatly help to know what I can do with my objects.

Community
  • 1
  • 1
BenoitParis
  • 3,166
  • 4
  • 29
  • 56

4 Answers4

16

If you include Underscore.js in your project, you can use _.functions(yourObject).

Allan Tokuda
  • 369
  • 3
  • 5
11

I think this is what you are looking for:

var obj = { locaMethod: function() { alert("hello"); }, a: "b", c: 2 };
for(var p in obj)
{
    if(typeof obj[p] === "function") {
      // its a function if you get here
    }
}
Mike Glenn
  • 3,359
  • 1
  • 26
  • 33
3

You should be able to enumerate methods that are set directly on an object, e.g.:

var obj = { locaMethod: function() { alert("hello"); } };

But most methods will belong to the object's prototype, like so:

var Obj = function ObjClass() {};
Obj.prototype.inheritedMethod = function() { alert("hello"); };
var obj = new Obj();

So in that case you could discover the inherited methods by enumerating the properties of Obj.prototype.

andrewmu
  • 14,276
  • 4
  • 39
  • 37
  • This is the issue I am running into in practice. I'll get everything that is in my object, but not Obj.prototype, and then if I remember, put my code here as an answer. I think this is introspection. Is there another term for this? – Brian Stinar Jul 14 '16 at 01:00
1

You can use the following:

var obj = { locaMethod: function() { alert("hello"); }, a: "b", c: 2 };


for(var p in obj)
{
    console.log(p + ": " + obj[p]); //if you have installed Firebug.
}
Giuseppe Romagnuolo
  • 3,362
  • 2
  • 30
  • 38