Arrays and Objects In Prototypes - Not Treated as References

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

    Define the array on the instance instead of on the prototype:

    function Test() {
        this.array = [];
    }
    
    Test.prototype.add = function (value) {
        this.array.push(value)
    }
    

提交回复
热议问题