简体   繁体   English

动态添加参数作为对象的属性 - JavaScript

[英]Dynamical adding of parameters as properties of object - JavaScript

I have a constructor function which can be used to instantiate a new Button object. 我有一个构造函数,可用于实例化一个新的Button对象。 When creating this object you can suffice the function with one argument. 创建此对象时,您可以使用一个参数满足该功能。 If this argument is an associative array, all the values of the array become properties of the Button object. 如果此参数是关联数组,则数组的所有值都将成为Button对象的属性。

So what I'm trying to do is this 所以我要做的就是这个

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
             });

What this should do is create a button object like this. 这应该做的是创建一个像这样的按钮对象。

button.name      //should be "My button"
button.value     //should be "My super special value",
button.color     //should be "black",
button.enabled   //should be false

I can't seem to figure out how to accomplish this, because if you get the association it is a string. 我似乎无法弄清楚如何实现这一点,因为如果你得到关联它是一个字符串。 And this.arg = args[arg] obviously won't work. 并且this.arg = args [arg]显然不起作用。

NOTE: the input must be an array, and if a user would put an total other associative array in as argument the properties will be different. 注意:输入必须是一个数组,如果用户将一个总的其他关联数组作为参数,则属性将不同。 {test:true} would dynamicaly create a button with a test property with the value true. {test:true}将动态创建一个带有test属性的按钮,其值为true。

This means button.test = true is not an option. 这意味着button.test = true不是一个选项。 It must be dynamic. 它必须是动态的。

并且this.arg = args[arg]显然不起作用

this[arg] = args[arg]

This 这个

function Button(args){ for (arg in args) { this[arg] = args[arg]; function Button(args){for(arg in args){this [arg] = args [arg]; } }; }};

var button = new Button({ name:"My button", value:"My super special value", color:"black", enabled:false }); var button = new Button({name:“My button”,value:“My super special value”,color:“black”,enabled:false});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM