Michael Connor
Michael Connor

Reputation: 4232

List of functions in the prototype

I'd like to be able to get a list of functions on different JavaScript objects, but specifically String and other primitives. I thought I would be able to somehow use String.prototype and magically get a list of the functions in the prototype but no dice. Any ideas?

I also tried using underscore. For example

_.functions("somestring");

...doesn't do it for me.

Upvotes: 5

Views: 1010

Answers (2)

adeneo
adeneo

Reputation: 318312

You'd use getOwnPropertyNames for that, it returns an array of all properties, enumerable or not

Object.getOwnPropertyNames(String.prototype)

FIDDLE

If you need only the functions (which would only exclude length I think ?) you could filter

var fns = Object.getOwnPropertyNames(String.prototype).filter(function(itm) {
    return typeof String.prototype[itm] == 'function';
});

FIDDLE

Upvotes: 4

thefourtheye
thefourtheye

Reputation: 239623

The actual problem is, the members of the primitive's prototype are not enumerable. So, we have to use Object.getOwnPropertyNames, which will give even the non-enumerable properties, to get them.

You can write a utility function, like this

function getFunctions(inputData) {
    var obj = inputData.constructor.prototype;
    return Object.getOwnPropertyNames(obj).filter(function(key) {
        return Object.prototype.toString.call(obj[key]).indexOf("Function") + 1;
    });
}
console.log(getFunctions("Something"));
console.log(getFunctions(1));

This filters all the properties which are Function objects and returns them as an Array.

Upvotes: 2

Related Questions