Llamar al constructor de JavaScript usando un arreglo para los argumentos
Tengo una función constructora en JavaScript como se muestra a continuación y quiero suministrar los argumentos del constructor desde un arreglo:
function dataRow(value1, value2, value3, value4, value5) {
this.val1 = value1;
this.val2 = value2;
this.val3= value3;
this.val4 = value4;
this.val5 = value5;
}
Ahora quiero que los argumentos del constructor se suministren desde un arreglo:
var dataArray = new Array();
dataArray("Value1","Value2","Value3","Value4","Value5","Value6"...........)
Quiero que (valor1, valor2, valor3, valor4, valor5) esta parte se llene desde mi dataArray.
Respuesta #1
En entornos modernos, puedes usar la notación de propagación:
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);En entornos más antiguos, es realmente un dolor hacer esto. En tu caso específico, probablemente simplemente hazlo a la manera difícil:
dataRow(dataArray[0], dataArray[1], dataArray[2], dataArray[3], dataArray[4]);
O puedes separar la creación de la llamada, y llamarla con 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);Eso no funcionaría con un constructor creado mediante class, pero si lo estás creando mediante class, usa la notación de propagación; se introdujeron al mismo tiempo (ES2015).
Sin embargo, sugeriría no hacer esto, especialmente a la luz de tu comentario de abajo:
...cómo crear esto dinámicamente this.val1=value1; this.val2=value2; this.val3= value3;...
En su lugar, usa una sola propiedad de arreglo y pasa un arreglo que mantengas o copies:
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);