I am sorry I do not know how to explain, but the situation is like this example.
After I instant a new function c
, and change the value this.i
will directly affect to a.
How can I solve this issue?? I do no know change this.i
will affect to a
.
var a = { c: 1 };
var b = function(){
this.i = a;
this.i.c = 2;
};
var c = function(){
this.i = a;
alert(this.i.c);
};
c.prototype.set = function(){
this.i.c = 4;
alert(a.c);
};
d =new c();
d.set();
I am sorry I do not know how to explain, but the situation is like this example.
After I instant a new function c
, and change the value this.i
will directly affect to a.
How can I solve this issue?? I do no know change this.i
will affect to a
.
http://jsbin./iPIkomu/1/edit
var a = { c: 1 };
var b = function(){
this.i = a;
this.i.c = 2;
};
var c = function(){
this.i = a;
alert(this.i.c);
};
c.prototype.set = function(){
this.i.c = 4;
alert(a.c);
};
d =new c();
d.set();
Share
Improve this question
asked Aug 18, 2013 at 21:07
MicahMicah
4,5608 gold badges32 silver badges40 bronze badges
3
-
2
If you don't want the object to be shared, then why are you making reference to the same object on every object created by your constructor? Was there some other purpose for the
var a = {...}
? Is there a reason it needs to be outside the constructor? I can't tell how to solve the issue because I don't know what you're ultimately trying to do. – user2437417 Commented Aug 18, 2013 at 21:10 - That is because a could be a default set of variables used for many constructor..will that make sense? – Micah Commented Aug 18, 2013 at 21:24
-
1
If it's to be used by several constructors, and you don't want to repeat the code, then either create it in a function as shown in the answer below, or use the shared object as a prototype of the main objects, and use
Object.create()
to set up the inheritance. So you'd dothis.i = Object.create(a);
– user2437417 Commented Aug 18, 2013 at 21:28
4 Answers
Reset to default 9Use this
let person1 = { name: 'Vitor', birthYear: 1995 };
// ES6 method
let person2 = Object.assign({}, person1);
In case of ArrayObject
let person1 = [{ name: 'Vitor', birthYear: 1995 },
{ name: 'Mark', birthYear: 1998 }];
// ES6 method
let person2 = Object.assign([], person1);
Refere to: https://hackernoon./javascript-reference-and-copy-variables-b0103074fdf0
Objects are always passed around by reference. a
and this.i
refer to the exact same object.
To get different objects, you'd need to just do this.i = {c:1};
or similar.
I'll suggest to change:
var a = { c: 1 };
to
var a = function() { return { c: 1 }; }
and then later
this.i = a;
to
this.i = a();
Doing the things like that you will be sure that you always get a new object. Using your code you are referring same object.
Since "a" is an object, therefore by equating them it passes the reference to "a", thereby making changes in both the variables. You can use any of the 2 methods -
this.i = JSON.parse(JSON.stringify(a));
OR
this.i = Object.assign({}, a);