Micah
Micah

Reputation: 4550

js Change variable will affect to original variable

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.com/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();

Upvotes: 2

Views: 5641

Answers (4)

Aayushi Singh
Aayushi Singh

Reputation: 31

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);

Upvotes: 2

Noaman Ilyas
Noaman Ilyas

Reputation: 655

Use 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.com/javascript-reference-and-copy-variables-b0103074fdf0

Upvotes: 9

Krasimir
Krasimir

Reputation: 13529

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.

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

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.

Upvotes: 4

Related Questions