bar*_*foo 5 javascript reflection naming
看看下面的代码片段.是否有任何函数可以替换...为生成路径,可以在另一个函数中重用?还是喜欢var route = this.show.fullyQualifiedName什么?
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);
}
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
不,没有,至少没有使用“反射”风格的操作。
对象不知道包含它们的对象的名称,尤其是因为同一对象(引用)可能包含在许多对象中。
唯一可以做到的方法是从顶部对象开始并向内操作,例如:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
这将_route在包含该对象路径的每个对象中放置一个新属性。
请参阅http://jsfiddle.net/alnitak/WbMfW/