0

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
5
  • 1
    You can't do that without calling method. Commented Jul 23, 2013 at 19:08
  • @Paulpro: It would be beyond difficult. It would be the halting problem. Commented Jul 23, 2013 at 19:08
  • Not to mention $.getJSON("...", function(result) { self[result.name] = function() { ... }) Commented Jul 23, 2013 at 19:09
  • And yes, there are libraries that do that. (eg, Google API client) Commented Jul 23, 2013 at 19:09
  • @SLaks You're right, it would be uncomputable. Commented Jul 23, 2013 at 19:10

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.