Reputation: 2193
I'm trying to write a "universal" array filler that fills an array with a given object. I simulted a class in javascript and now I want to write a function that fills the array with types of that class
function fillArray(theArrayToFill,amount,theObject) {
for ( var i = 0; i != amount; ++i )
{theArrayToFill.push(theObject);}
}
But fillArray (theArray,3,new Enemy(0,0)); fills the array with a reference to that object "enemy" and that's not what I want, I want an exact copy, but when I mutate object 0, object 2 may not change.
Please Help Thanks
Upvotes: 0
Views: 104
Reputation: 1462
If you are using Underscore, it provides a clone helper function.
function fillArray(theArrayToFill,amount,theObject) {
for ( var i = 0; i != amount; ++i )
{theArrayToFill.push(_.clone(theObject));}
}
Upvotes: 0
Reputation: 13381
you can use Object.create()
function fillArray(theArrayToFill,amount,theObject) {
for ( var i = 0; i != amount; ++i ) {
theArrayToFill.push(Object.create(theObject));
}
}
or if you want return new array filled default value you can use next code
function fillArray(amount,theObject) {
return Array.apply(null,Array(amount)).map(function(_){return Object.create(theObject);});
}
Upvotes: 0
Reputation: 27823
Since you already have the constructor, here is how you can use it:
function fillArray(theArrayToFill,amount,ctor) {
for ( var i = 0; i != amount; ++i ) {
theArrayToFill.push(new ctor(0,0));
}
}
// usage:
fillArray(theArray,3,Enemy);
The way you originally called the fillArray method, you created one object (immediately before the function is called) and passed it as parameter to the fillArray method. The method then proceded to fill the array with references towards that object, so each item in the array would indeed point towards the same object.
EDIT: No simple solution comes to mind if you want to pass different arguments to the constructor. Here is a hacky one that might be enough for your purposes:
function fillArray(theArrayToFill,amount,ctor) {
for ( var i = 0; i != amount; ++i ) {
theArrayToFill.push(new ctor(arguments[3], arguments[4], arguments[5],
arguments[6], arguments[7], arguments[8], arguments[9], arguments[10],
arguments[11], arguments[12], arguments[13], arguments[14]));
}
}
// usage:
fillArray(theArray,3,Enemy,0,0);
fillArray(theArray,3,Friend,1,2,3,4,5,6,7,8);
Obviously this only works for constructors with less than 12 arguments and some checks based on used parameters in a constructor will also fail, but it gets the job done.
PS: I don't suggest you use this approach. Looks like a clone method is more suited to your purpose.
Upvotes: 0
Reputation: 1570
I would recommend you to add a clone method to your object. The clone method should create a new object and set it's value by copying the current object, then the method return this new object.
example:
function clone(obj)
{
var newObj = new YourObject();
newObj.setName(obj.getName());
//Do this for every properties
return newObj;
}
Upvotes: 1