我正在用一种转换表构建一个与画布相关的类。转换表可以由用户编辑。(并不是真的相关,但也许你想知道原因):
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.width。但是我想使用没有第二对括号的el[something]:我希望属性名是完全可变的(我也希望能够设置el['innerHTML'])。那么,有什么方法可以不用a[b]而不用a[b][c]来获得孙女呢?
当然,我不想用。
发布于 2011-06-18 12:42:04
不不可能。如果有嵌套对象,则不能跳过级别。
不过,您可以编写一个助手函数,它接受一个类似于"child.grandchild"的字符串,并设置相应的属性:
function setProp(obj, prop, val) {
var parts = prop.split('.');
while(parts.length > 1) {
obj = obj[parts.shift()];
}
obj[parts.shift()] = val;
}(您还应该测试某个属性是否可用。)
那么您的代码看起来可能是:
var cLayout = function(option) {
//obtaining the canvas (el) here
this.setup = function(option) {
for(var p in this.table) {
setProp(el, this.table[p][0], option[p]||t[p][1]);
}
}
this.setup(option)
}
cLayout.prototype.table = {
width:['style.width',"100%"],
height:['style.height',"100%"],
//...
}https://stackoverflow.com/questions/6395976
复制相似问题