2011-06-18 6 views
5

Estoy construyendo una clase relacionada con el lienzo con un tipo de tabla de conversión. La tabla de conversión puede ser editada por el usuario. (No es realmente relevante, pero tal vez usted quiere saber por qué):Nieto de acceso de una variable (parent.child.grandchild) sin puntos y un par de corchetes

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"] 
} 

Ejemplo:

var b = new cLayout({left:'10%',width:'90%'}) 

pregunta real:

Normalmente, usaría a el['style']['width'] establecer el.style.width. Pero quiero usar el[something] sin el segundo par de corchetes: quiero que el nombre de la propiedad sea completamente variable (también deseo poder establecer el['innerHTML']). Entonces, ¿hay alguna manera de obtener un nieto usando a[b], sin usar a[b][c]?

P.S. Por supuesto, no quiero usar eval.

+0

Este '[['style'] ['width']," 100% "]' no tiene sentido. Tratará de acceder a la propiedad 'width' de la matriz' ['style'] ', que es' undefined'. Entonces lo que obtienes es '[indefinido," 100% "]'. Similar para '['style' ['left']," 0px "]'. –

+0

Lo sé. Es lo que me gustaría tener, pero no funciona, por supuesto. – bopjesvla

Respuesta

3

No, no es posible. Si tiene objetos anidados, no puede saltear un nivel.

Se podría escribir una función de ayuda, sin embargo, que toma una cadena como "child.grandchild" y establece la propiedad correspondiente: (. También debe probar si una determinada propiedad está disponible)

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

Luego, su el código podría verse así:

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

¡Eres increíble! – bopjesvla

Cuestiones relacionadas