Domanda

I am using a plain JavaScript object. I have to create an exact copy of the object to make changes:

var gRoll = {a:"pankaj",b:
{
a:"A",b:"c"
}} 

var copy = gRoll;
copy.a = "Karma";

This is making change in the parent object. Please give me solution to create copy of the object without referring to the old one. Same like prototype design pattern in OOPS.

È stato utile?

Soluzione

You're referencing the same object with copy

var gRoll = {
    a:"pankaj",
    b:{a:"A",b:"c"}
}
var newObject = Object.create(gRoll);
newObject.a = 'Karma';

alert(gRoll.a); //pankaj
alert(newObject.a); //Karma

Altri suggerimenti

what you are doing is not creating a copy but referring to the existing object with a new variable, hence the issue.

If you are using jQuery, use its extend() method which copies an exiting object... with optional parameter for deep-copying. http://api.jquery.com/jquery.extend/

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top