Arrays and Objects In Prototypes - Not Treated as References

前端 未结 4 1412
我在风中等你
我在风中等你 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:31

    Initialize mutable members in the constructor, not in the prototype. If it's in the prototype, it will be shared between all instances:

    let Test = function () {
        this.array = [];
    }
    
    Test.prototype = {
        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);
    console.log(test2.array);

提交回复
热议问题