Add parameters dynamically as object properties - JavaScript

I have a constructor function that can be used to instantiate a new Button object. When creating this object, one argument may suffice. If this argument is an associative array, all array values ​​become properties of the Button object.

So what I'm trying to do is

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 cannot figure out how to do this, because if you get an association, this is a string. And this.arg = args [arg] will obviously not work.

NOTE: the input must be an array, and if the user would place a common other associative array as an argument, the properties will be different. {test:true} will dynamically create a button with a test property with a value of true.

This means that button.test = true not an option. It must be dynamic.

+4
source share
2 answers

And this.arg = args[arg] obviously not work

 this[arg] = args[arg] 
+5
source

it

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

var button = new Button ({name: "My button", value: "Mine over special value", black color, included: false});

0
source

Source: https://habr.com/ru/post/1399364/


All Articles