访问没有点和一对括号的变量(parent.child.grandchild)的孙

bop*_*vla 5 javascript oop canvas square-bracket

我正在使用一种转换表构建一个与画布相关的类.转换表可由用户编辑.(不是真的相关,但也许你想知道为什么):

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"]
}
Run Code Online (Sandbox Code Playgroud)

例:

var b = new cLayout({left:'10%',width:'90%'})
Run Code Online (Sandbox Code Playgroud)

真实的问题:

通常,我会el['style']['width']用来设置el.style.width.但我想在el[something]没有第二对括号的情况下使用:我希望属性名称完全可变(我也希望能够设置el['innerHTML']).那么,有没有办法让孙子使用a[b],而不使用a[b][c]

PS当然,我不想使用eval.

Fel*_*ing 4

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

不过,您可以编写一个辅助函数,它接受类似的字符串"child.grandchild"并设置相应的属性:

function setProp(obj, prop, val) {
    var parts = prop.split('.');
    while(parts.length > 1) {
        obj = obj[parts.shift()];
    }
    obj[parts.shift()] = val;
}
Run Code Online (Sandbox Code Playgroud)

(您还应该测试某个属性是否可用。)

那么你的代码可能如下所示:

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%"],
    //...
}
Run Code Online (Sandbox Code Playgroud)