4

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.

2 Answers 2

5

And this.arg = args[arg] obviously won't work

this[arg] = args[arg]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks!, I'm a bit embarrassed for the answer being this simple.
@Rick Hoving You should not be embarrassed, you are not the only one who encounters this problem haha ;)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.