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.

有帮助吗?

解决方案

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

其他提示

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/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top