Arrays and Objects In Prototypes - Not Treated as References

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

    I understand that arrays and objects are passed by reference

    No, they are not. But they're referenced by object references, which is an entirely different thing,1 and is indeed the issue you're running into.

    and was wondering of a solution that would get you around this?

    Do exactly what you did in the ES6 approach: Put it on the object itself, not the prototype:

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

    1 (All that the concepts "pass by reference" and "object reference" have in common is that they both use the word "reference." In the former, it's a reference to a variable [and a concept JavaScript doesn't have]. In the latter, it's a reference to an object.)

提交回复
热议问题