Edit: I've slightly misread the question, you want to extract the names of only the properties that are function objects:
function methods(obj) {
var result = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && typeof obj[prop] == 'function') {
result.push(prop);
}
}
return result;
}
var obj = {
foo: function() { },
bar: function() { },
};
methods(obj); // ["foo", "bar"]
I'm using the hasOwnProperty
method, to ensure that the enumerated properties in fact exist physically in the object.
Note that this approach and all other answers have a small problem IE.
The JScript's DontEnum Bug, custom properties that shadow non-enumerable properties (DontEnum
) higher in the prototype chain, are not enumerated using the for-in statement, for example :
var foo = {
constructor : function() { return 0; },
toString : function() { return "1"; },
valueOf : function() { return 2; }
toLocaleString : function() { return "3"; }
};
for (var propName in foo ) { alert(propName); }
The object foo
clearly has defined four own properties, but those properties exist in Object.prototype
marked as DontEnum
, if you try to enumerate the properties of that object with the for-in
statement in IE, it won't find any.
This bug is present on all IE versions, and has been recently fixed in IE9 Platform Preview.