Javascript Constructors with an Array of Parameters
by Peter.
Say we have:
function myObj() { this.input = Array.prototype.slice.call(arguments); } |
We can pass a variable or an array but :
var myObj1 = new myObj(1); myObj1.input // -> [1] var myArr = [1, 2, 3]; var myObj2 = new myObj(myArr); myObj2.input // -> [[1, 2, 3]] |
How then can we get, while still using myArr:
myObj3.input // -> [1, 2, 3] |
Here’s how, courtesy of this site:
var myObj3 = new myObj(); myObj.prototype.constructor.apply(myObj3, myArr); |
Note that myObj3
needn’t be an instance of myObj
, it just needs to be an existing value so that the global object isn’t used as the value of this
.
This is pretty cool, though of course you can do it much easier in languages such as Scala:
val myObj4 = new myObj(myArr: _*) |