I have a constructor function in JavaScript as below and want to supply constructor arguments from an array:
function dataRow(value1, value2, value3, value4, value5) {
this.val1 = value1;
this.val2 = value2;
this.val3= value3;
this.val4 = value4;
this.val5 = value5;
}
Now I want the constructor arguments supplied from an array:
var dataArray = new Array();
dataArray("Value1","Value2","Value3","Value4","Value5","Value6"...........)
I want (value1, value2, value3, value4, value5) this part to filled from my dataArray
.
In modern environments, you can use spread notation:
var row = new dataRow(...dataArray);
function dataRow(v1, v2, v3, v4, v5) {
this.v1 = v1;
this.v2 = v2;
this.v3 = v3;
this.v4 = v4;
this.v5 = v5;
}
var dataArray = [1, 2, 3, 4, 5];
var row = new dataRow(...dataArray);
console.log(row.v1);
console.log(row.v2);
console.log(row.v3);
console.log(row.v4);
console.log(row.v5);
In older environments, it's a real pain to do this. In your specific case, probably just do it the hard way:
dataRow(dataArray[0], dataArray[1], dataArray[2], dataArray[3], dataArray[4]);
Or you can separate creation from the call, and call it with Function#apply
:
var row = Object.create(dataRow.prototype);
dataRow.apply(row, dataArray);
function dataRow(v1, v2, v3, v4, v5) {
this.v1 = v1;
this.v2 = v2;
this.v3 = v3;
this.v4 = v4;
this.v5 = v5;
}
var dataArray = [1, 2, 3, 4, 5];
var row = Object.create(dataRow.prototype);
dataRow.apply(row, dataArray);
console.log(row.v1);
console.log(row.v2);
console.log(row.v3);
console.log(row.v4);
console.log(row.v5);
That wouldn't work with a constructor created via class
, but if you're creating it via class
, use spread notation; they were introduced as the same time (ES2015).
I would suggest not doing this, though, especially in light of your comment below:
...how to create this dynamically this.val1 = value1; this.val2 = value2; this.val3= value3;...
Instead, use a single array property, and pass in an array which you either keep or copy:
function dataRow(values) {
this.values = values;
// or: this.values = values.slice();
// to make a shallow copy
}
var dataArray = [1, 2, 3, 4, 5];
var row = new dataRow(dataArray);
console.log(row.values);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With