2012-04-13 90 views
0

如何将属性动态添加到Javascript对象/类中?将XML名称值对动态转换为对象属性

我解析一个xml文件,为xml元素中的每个名称值对我试图将该对添加为一个Javascript对象的属性。为清晰起见,请参阅我的示例:

function MyObject(nType) 
{ 
    this.type = nType; 
} 

MyObject.prototype.parseXMLNode(/*XML Node*/ nodeXML) 
{ 
    var attribs = nodeXML.attributes; 
    for (var i=0; i<attribs.length; i++) 
     this.(attribs[i].nodeName) = attribs[i].nodeValue; // ERROR here 
} 

// Where the xml would look like 
<myobject name="blah" width="100" height="100"/> 

回答

1

您已经非常接近了。要在对象上动态调用和分配属性,您需要使用括号表示法。

例如:

person = {} 
person['first_name'] = 'John' 
person['last_name'] = 'Doe' 

// You can now access the values using: 
// person.first_name OR person['last_name'] 

以下应为你工作:

MyObject.prototype.parseXMLNode(nodeXML) { 
    var attrs = nodeXML.attributes, 
     length = attrs.length; 

    for(var i=0; i < length; i++) { 
     this[attrs[i].nodeName] = attrs[i].nodeValue; 
    } 
}