-1

I'm reading through a textbook on Javascript and there is an example of shallow cloning vs deep cloning of objects.

Can anyone give me an example why I would want to clone an object instead of using the 'new' keyword ?

For example, in a simple game,if I have 10 enemy objects, I would create a constructor called 'enemy' and create new enemies with the 'new' keyword.

stckpete
  • 571
  • 1
  • 4
  • 13

1 Answers1

1

The new operator creates an instance of the object from the details mentioned in the class/function. Now say you have created an object and changed/added some property to it. Next time you use the new keyword, you won't get the changes made above. Cloning would actually give you a new object with the changed values.

Lets take an example:

function Car() {}
myCar = new Car();
console.log(myCar.color);    // you'll get undefined
myCar.color = "red";
console.log(myCar.color);    // you'll get red

// now create another object
yourCar = new Car();
console.log(yourCar.color);    // you'll still get undefined

// if you clone
yourCar = clone(myCar) // assume you have some clone method
console.log(yourCar.color);    // Now you'll get red

In your case, if you have created 10 'enemies' object. At some point in the game you may have set some properties for those enemies object. If you use new operator, those changes won't reflect in the new object. However if you clone the enemies object, you will get a new object along with the changes made before.

If you are interested in shallow copy vs deep copy, it's answered at What is the difference between a deep copy and a shallow copy?

Community
  • 1
  • 1
Anurag Sinha
  • 1,014
  • 10
  • 17