Arrays and Objects In Prototypes - Not Treated as References

前端 未结 4 1416
我在风中等你
我在风中等你 2021-01-27 00:48

I have a prototype object in Javascript, when I initialise a new instance of the prototype and update properties in the prototype, it updates for all elements. I understand that

4条回答
  •  星月不相逢
    2021-01-27 01:25

    That's the thing: they are treated as references.

    When you do this:

    Test.prototype = {
        array: [], // <- This creates a new array and it's being used in all instances
        add: function (value) {
            this.array.push(value)
        }
    }
    

    What you want is getting different array instances for different class instances. In that case, simply do this.array = [] in your constructor:

    let Test = function () { this.array = []; }
    

    let Test = function () { this.array = []; }
    
    Test.prototype = {
        array: [],
        add: function (value) {
            this.array.push(value)
        }
    }
    
    let test1 = new Test();
    let test2 = new Test();
    
    test1.add(1);
    test1.add(2);
    
    console.log(test1.array);
    // => [1, 2]
    
    console.log(test2.array);
    // => []

提交回复
热议问题