zoplonix
zoplonix

Reputation: 1072

Get all functions that exist in JavaScript object (including nested functions)

Is it possible to get all of the functions in a JavaScript object?

Consider the following object:

var myObject = 
{ 
    method: function () 
    { 
        this.nestedMethod = function () 
        { 
        } 
    },
    anotherMethod: function() { } 
});

If I pass it into the function below I will get this result:

method
anotherMethod

(function to get all function names)

function properties(obj) 
{
    var output = "";
    for (var prop in obj) {
        output += prop + "<br />";
        try
        {
            properties(obj[prop]);
        }
        catch(e){}
    }
    return output;
}

How can I make this output:

method
nestedMethod
anothermethod

Upvotes: 0

Views: 67

Answers (2)

seymar
seymar

Reputation: 4063

You are iterating through the elements of objects. The function in the object is not an object. So just create an object from the function, and iterate over it to check it.

This works:

function properties(obj) {
    var output = "";
    for (var prop in obj) {
        output += prop + "<br />";

        // Create object from function        
        var temp = new obj[prop]();

        output += properties(temp);
    }

    return output;
}

Fiddle: http://jsfiddle.net/Stijntjhe/b6r62/

It's a bit dirty though, it doesn't take arguments in consideration.

Upvotes: 0

SLaks
SLaks

Reputation: 887777

nestedMethod is only created after running the function.

You can call every function on the object to see if they create more functions, but that's a horrible idea.

Upvotes: 3

Related Questions