0

Basically the code says everything. I have a variable x with a css property. I'm saving all the css of x into y, and then I change the value of the y's property. This change also affects x, why? How to make it to only pass the value so that x stays unchanged?

var x = {};
x.css = {height: 100, width: 100};

var y = {};
y.css = x.css;
y.css.height = 200;

console.log(x.css.height); //equals to 200 while it should be 100
dodo254
  • 519
  • 2
  • 7
  • 16

2 Answers2

1

You're creating an object and then pointing two different variables at the same object. The most simplest explanation would be that you're are just giving variable x another name/variable accessor. Look at the below example to see how to overcome this, or you can create a copy of the object.

Solution 1: Use this trick to clone an object.

var x = {};
x.css = {height: 100, width: 100};

var y = JSON.parse(JSON.stringify(x));
y.css.height = 200;

console.log('Y Height:', y.css.height);
console.log('X Height:', x.css.height);

Solution 2: Create a new instance that has it's own local properties

var elementInstance = function() {
  return {
    css: {
      height: 100,
      width: 100
    }
  }
}

var x = new elementInstance();
var y = new elementInstance();

y.css.height = 200;

console.log(x, y); // They should be different instances
Win
  • 5,498
  • 2
  • 15
  • 20
1

Javascript assignment is done by reference and hence your x.css is also modified when you modify y.css . You can rather assign y.css using Object.assign.

var x = {};
x.css = {height: 100, width: 100};

var y = {};
y.css = Object.assign({}, x.css);
y.css.height = 200;

console.log(x.css.height);
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400