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

房东的猫 提交于 2019-12-05 09:17:02

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/

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!