Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 828
Michael Connor Avatar asked May 02 '14 15:05

Michael Connor


People also ask

What are the many functions of a prototype?

1) It tells the return type of the data that the function will return. 2) It tells the number of arguments passed to the function. 3) It tells the data types of each of the passed arguments. 4) Also it tells the order in which the arguments are passed to the function.

What is prototype of a function?

A function prototype is a definition that is used to perform type checking on function calls when the EGL system code does not have access to the function itself. A function prototype begins with the keyword function, then lists the function name, its parameters (if any), and return value (if any).

What is function prototyping in C?

A function prototype is simply the declaration of a function that specifies function's name, parameters and return type. It doesn't contain function body. A function prototype gives information to the compiler that the function may later be used in the program.

Which of the following is a correct example of function prototype?

Answer: void function ();


2 Answers

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

like image 139
adeneo Avatar answered Oct 21 '22 03:10

adeneo


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.

like image 27
thefourtheye Avatar answered Oct 21 '22 02:10

thefourtheye