문제

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