我有一个构造函数,可用于实例化一个新的 Button 对象。创建此对象时,您可以使用一个参数来满足该函数的需求。如果此参数是一个关联数组,则该数组的所有值都将成为 Button 对象的属性。
所以我想做的就是这个
function Button(args){
for (arg in args)
{
//Add the name of arg as property of Button with arg as value.
}
};
var button = new Button({
name:"My button",
value:"My super special value",
color:"black",
enabled:false
});
这应该做的是创建一个像这样的按钮对象。
button.name //should be "My button"
button.value //should be "My super special value",
button.color //should be "black",
button.enabled //should be false
我似乎无法弄清楚如何完成此操作,因为如果您获得关联,它就是一个字符串。而 this.arg = args[arg] 显然是行不通的。
注意:输入必须是一个数组,如果用户将一个总的其他关联数组作为参数放入,则属性将不同。 {test:true}
将动态创建一个带有值为 true 的测试属性的按钮。
这意味着 button.test = true
不是一个选项。它必须是动态的。
最佳答案
And
this.arg = args[arg]
obviously won't work
this[arg] = args[arg]
关于javascript - 动态添加参数作为对象的属性 - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9531427/