2011-06-18 22 views
5

我正在用一種轉換表建立一個與canvas有關的類。轉換表可以由用戶編輯。 (是不是真的有關,但也許你想知道爲什麼):訪問沒有點和一對括號的變量(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.width。 但我想使用el[something]沒有第二對括號:我希望屬性名稱是完全可變的(我也希望能夠設置el['innerHTML'])。那麼,有沒有辦法通過使用a[b]來獲得孫子,而不使用a[b][c]

P.S.當然,我不想使用eval。

+0

這種'[['style'] ['width'],「100%」]'沒有意義。它將嘗試訪問'['style']'數組的'width'屬性,該數組是'undefined'。所以你得到的是'[未定義,「100%」]。類似於['style'['left'],「0px」]'。 –

+0

我知道。這是我想要的,但它當然不起作用。 – bopjesvla

回答

3

不,這是不可能的。如果你有嵌套的對象,你不能只跳過一個關卡。

你可以寫,雖然一個輔助函數,它接受一個字符串像"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%"], 
    //... 
} 
+0

你太棒了! – bopjesvla