Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Getting fully-qualified function name from within it?

Take a look at the snippet below. Is there any function I could write in replace of ... to generate the route, that could reused in another function? Something like var route = this.show.fullyQualifiedName perhaps?

var services = {
    'github.com': {
        api: {
            v2: {
                json: {
                    repos: {
                        show: function(username, fn) {
                            var route = ...; 
                            // route now == 'github.com/api/v2/json/repos/show'

                            route += '/' + username;

                            return $.getJSON('http://' + route).done(fn);
                        }
                    }
                }
            }
        }
    }
}
like image 694
barfoo Avatar asked Oct 07 '22 23:10

barfoo


2 Answers

No, there isn't, at least not using "reflection" style operations.

Objects have no knowledge of the name of the objects in which they're contained, not least because the same object (reference) could be contained within many objects.

The only way you could do it would be to start at the top object and work your way inwards, e.g.:

function fillRoutes(obj) {
    var route = obj._route || '';
    for (var key in obj) {
        if (key === '_route') continue;
        var next = obj[key];
        next._route = route + '/' + key;
        fillRoutes(next);
    }
}

which will put a new _route property in each object that contains that object's path.

See http://jsfiddle.net/alnitak/WbMfW/

like image 190
Alnitak Avatar answered Oct 13 '22 09:10

Alnitak


You can't do a recursive search, like Alnitak said, but you could do a top-down search, although it could be somewhat slow depending on the size of your object. You'd loop through the object's properties, checking to see if it has children. If it does have a child, loop through that, etc. When you reach the end of a chain and you haven't found your function, move to the next child and continue the search.

Don't have the time to write up an example now, but hopefully you can piece something together from this.

like image 32
Elliot Bonneville Avatar answered Oct 13 '22 10:10

Elliot Bonneville