0
    var a = {

        b: {
            aa: 'hello',
            bb: 'you',
            cc: 'guys'
            }

    }


    var b = function(){ 

        $.each(a.b, function(x){                

            if( $.isFunction(x) == 'function' ){
                alert(x);
            };

        });

    };

    var aa = function(){
        var dude = 'hi there';
    }

    b();

I have an each loop inside the b function.

What i would like to do is loop through the a.b values, and find if a function exists with it's name. In this case the only one that should trigger is 'aa' as function 'aa exists.

is the isfunction line correct? or would typeof work?

Amit
  • 15,217
  • 8
  • 46
  • 68
Robert Hane
  • 37
  • 1
  • 4
  • var aa and the aa within your a object are two completely different values due to namespace and scope. So if you are looking to find var aa within your object you need to push it into a.b – Scott Sword Jun 17 '13 at 02:29

1 Answers1

2

In this case the only one that should trigger is 'aa' as function 'aa exists.

$.each() is iterating members of the Object passed to it. And, currently, the function aa is not a member of the Object a.b.

$.isFunction() isn't returning true because every member of a.b has a String value:

aa: 'hello',
bb: 'you',
cc: 'guys'

If you want the function as a member of the Object, you'll need to set it as the value of one of its properties:

a.b.aa = function () {
    var dude = 'hi there';
};

This will replace the 'hello' value with a reference to the function.


To reuse the property names to lookup globals, you can use them on the global object (window in browsers).

var key = 'aa';
var val = window[key];
var b = function () {
    $.each(a.b, function (key) {
        if (key in window && $.isFunction(window[key])) {
            alert(key + ' is a global function.');
        }
    });
};

Example: http://jsfiddle.net/cAaMf/

Though, note the "No wrap - in <body>" in the options of the Fiddle. This will only work for globals as no other scope object can be accessed within code.

Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199