JavaScript:从中获取完全限定的函数名称? [英] JavaScript: Getting fully-qualified function name from within it?

查看:89
本文介绍了JavaScript:从中获取完全限定的函数名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看下面的代码段。是否有任何函数可以替换 ... 来生成可以在另一个函数中重用的路径?类似 var route = this.show.fullyQualifiedName 或许?

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


推荐答案

不,没有,至少没有使用反射式操作。

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

这会产生一个新的包含该对象路径的每个对象中的_route 属性。

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

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

这篇关于JavaScript:从中获取完全限定的函数名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆