JavaScript: How to get the full function name from the inside?

Take a look at the snippet below. Is there any function that I could write instead ...to generate a route that could be reused in another function? Is something like that var route = this.show.fullyQualifiedNamepossible?

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);
                        }
                    }
                }
            }
        }
    }
}
+5
source share
2 answers

No, no, at least not use reflection-style operations.

Objects do not know the names of the objects in which they are contained, not least because the same object (link) can be contained in many objects.

The only way you could do this is to start from the top object and go your way inward, for example:

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);
    }
}

_route , .

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

+3

, Alnitak, , . , , . , .. , .

, , , , - .

+1

All Articles