Method 1:
The simplest of achieving this is to use new in combination with the Function constructor.
var myStruct = function(prop1,prop2){ this.prop1 = prop1; this.prop2 = prop2; } var myStructObj = new myStruct(); var myStructObj2 = new myStruct("prop1","prop2"); var myArr = []; myArr.push(myStructObj); myArr.push(myStructObj2); console.log(myArr);
An enhancement would be to add default params to the constructor and pass arguments while creation.
var myStruct = function(arg1, arg2){ var prop1 = arg1 || "defaultProp1Value"; var prop2 = arg2 || "defaultProp2Value"; this.prop1 = prop1; this.prop2 = prop2; } var myStructObj1 = new myStruct(); //myStructObj1.prop1 is "defaultProp1Value" //myStructObj1.prop2 is "defaultProp2Value" var myStructObj2 = new myStruct("prop1"); //myStructObj2.prop1 is "prop1" //myStructObj2.prop2 is "defaultProp2Value" var myArr = []; myArr.push(myStructObj1); myArr.push(myStructObj2);
With ES6, you can do this, you can now add default parameters to the constructor.
//This only works in ES6 // Will cause errors on browsers which have not yet added support // WIll work when used along with a transpiler like Babel var myStruct = function(arg1 = "defaultProp1", arg2 = "defaultProp2"){ this.prop1 = arg1; this.prop2 = arg2; } var myStructObj1 = new myStruct(); //myStructObj1.prop1 is "defaultProp1Value" //myStructObj1.prop2 is "defaultProp2Value" var myStructObj2 = new myStruct("prop1"); //myStructObj2.prop1 is "prop1" //myStructObj2.prop2 is "defaultProp2Value" var myArr = []; myArr.push(myStructObj1); myArr.push(myStructObj2); console.log(myArr);
You can read more about it here
Method : 2
Using call method. With this approach you can add props on the fly. Whenever you want to add a couple of props to an object with either null values or default values you can use this approach.
var addPropsFunction = function(a,b){ this.prop1 = a; this.prop2 = b; } var myObj1 = {}; var myObj2 = {}; addPropsFunction.call(myObj1); addPropsFunction.call(myObj2,"val1","val2"); console.log(myObj1); console.log(myObj2);
Method : 3
ES6 Classes
class myStruct{ constructor(prop1,prop2){ this.prop1 = prop1; this.prop2 = prop2; } } var myObj = new myStruct(); console.log(myObj);
Es6 Fiddle - http://www.es6fiddle.net/ifz3rjcc/
In all cases, changing properties is the same. To change prop1's value, all you have to do is
myStructObj.prop1 = "my val";