Reputation: 3575
I have a constructor function which can be used to instantiate a new Button object. 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.
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.
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.
This means button.test = true
is not an option. It must be dynamic.
Upvotes: 4
Views: 2911
Reputation: 2677
This
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 });
Upvotes: 0
Reputation: 944175
And
this.arg = args[arg]
obviously won't work
this[arg] = args[arg]
Upvotes: 5