访问变量(parent.child.sgrandschild)的孙子,不带点和一对括号

Access grandchild of a variable (parent.child.grandchild) without dots and one pair of brackets

本文关键字:parent 变量 child sgrandschild 访问      更新时间:2023-09-26

我正在用一种转换表构建一个与画布相关的类。用户可以编辑转换表。(其实并不相关,但也许你想知道原因):

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][c]的情况下使用a[b]生孙子?

第页。S.当然,我不想用eval。

不,这是不可能的。如果有嵌套对象,则不能仅跳过一个级别。

不过,您可以编写一个helper函数,它采用类似"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%"],
    //...
}