访问变量的孙子(parent.child.grandchild),不带点和一对括号
我正在使用一种转换表构建一个与画布相关的类。用户可以编辑转换表。 (并不是真正相关,但也许你想知道为什么):
cLayout = function(option) {
//obtaining the canvas (el) here
this.setup = function(option) {
t=this.table;
for (var p in t)
{
el[t[p][0]] = option[p]||t[p][1]
}
}
this.setup(option)
}
cLayout.prototype.table = {
width:[['style']['width'],"100%"],
height:['style'['height'],"100%"],
bg:[['style']['backgroundColor'],""],
position:[['style']['position'],"absolute"],
left:['style'['left'],"0px"],
top:['style'['left'],"0px"]
}
示例:
var b = new cLayout({left:'10%',width:'90%'})
真正的问题:
通常,我会使用 el['style']['width'] 来设置 el.style 。宽度。 但我想使用 el[something] 而不使用第二对括号:我希望属性名称完全可变(我还希望能够设置 el['innerHTML'] )。那么,有没有一种方法可以通过使用a[b]
来获取孙子,而不使用a[b][c]
呢?
PS 当然,我不想使用eval。
I'm building a canvas-related class with a kind of conversion table. The conversion table can be edited by the user. (Isn't really relevant, but maybe you want to know why):
cLayout = function(option) {
//obtaining the canvas (el) here
this.setup = function(option) {
t=this.table;
for (var p in t)
{
el[t[p][0]] = option[p]||t[p][1]
}
}
this.setup(option)
}
cLayout.prototype.table = {
width:[['style']['width'],"100%"],
height:['style'['height'],"100%"],
bg:[['style']['backgroundColor'],""],
position:[['style']['position'],"absolute"],
left:['style'['left'],"0px"],
top:['style'['left'],"0px"]
}
Example:
var b = new cLayout({left:'10%',width:'90%'})
Real question:
Normally, I'd use el['style']['width']
to set el.style.width.
But I want to use el[something]
without the second pair of brackets: I want the property name to be completely variable (I also want to be able to set el['innerHTML']
). So, is there a way to get a grandchild by using a[b]
, without using a[b][c]
?
P.S. Of course, I don't want to use eval.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,这是不可能的。如果您有嵌套对象,则不能直接跳过一个级别。
不过,您可以编写一个辅助函数,它接受像
"child.grandchild"
这样的字符串并设置相应的属性:(您还应该测试某个属性是否可用。)
然后您的代码可能如下所示:
No it is not possible. If you have nested objects, you cannot just skip a level.
You could write a helper function though, which takes a string like
"child.grandchild"
and sets the corresponding property:(You should also test whether a certain property is available.)
Then your code could look like: