0

sorry by question but i'm not so very well in JavaScript, and I searched but did not find the answert, I hope you'll help me. I have this code

var obj = {
    var1:[],
    var2:[],
    set1: function(){
        this.var1.push(1);
    },
    set2 : function(){
        this.var2 = this.var1;
    }
 };

 obj.set1();
 obj.set2();
 obj.set1();

 console.log(obj.var2);

I think that in console will be [1], but the correct is [1,1] Question is How to set var2 in set2 to have [1] in console. I think that this.var2 = this.var1; is the reference, but I realy need to set var2 to var1

Marin Vartan
  • 572
  • 7
  • 16
  • 2
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty – EasyBB Oct 30 '15 at 12:35

1 Answers1

2

Yes you assign it by reference. You need to copy the array instead. I modified your code a little bit.

var obj = {
    var1:[],
    var2:[],
    set1: function(){
        this.var1.push(1);
    },
    set2 : function(){
        this.var2 = this.var1.slice()
    }
 };

 obj.set1();
 obj.set2();
 obj.set1();

 console.log(obj.var2);

The array.slice() method will return a new array with same values.

memo
  • 273
  • 2
  • 15