Javascript object members that are prototyped as arrays become shared by all class instances

前端 未结 3 759
日久生厌
日久生厌 2020-11-22 08:40

Has anyone noticed this behavior before? This really threw me off... I would have expected prototyped arrays to be private to each class instance rather than shared between

3条回答
  •  名媛妹妹
    2020-11-22 09:37

    When you do var exp1 = new C(), JavaScript sets exp1.[[Prototype]] = C.prototype. When you then access properties of the instance, JavaScript first checks whether they exist on that object directly, and if not, it looks in [[Prototype]]. This means that all the stuff you define in prototype is effectively shared by all instances, and you can even later change parts of prototype and have the changes appear in all existing instances.

提交回复
热议问题