Javascript inheritance is very different from standard oop inheritance. Javascript inheritance uses prototype chain technology. Each class will put "member variables" and "member functions" on the prototype. Js all use superclass Link it up, i.e. C.prototype.superclass = C.superclass = P.prototype;
When var c = new C(), c.__proto__ = C.prototype;
When c accesses "member variable ", if __proto__ cannot be obtained, it will search in C.prototype. If it does not exist, it will search in the prototype of the parent class, because only __proto__ is allocated when the object is created (each object is allocated independently ), others are allocated when defining (shared by each object). At this time, if the "member variable" in C.prototype is accessed as an object, the "member variable" itself will not be modified, but the "member variable" object will be modified. When modifying the members of the "member variable" object, the members of the modified "member variable" object will be shared by all object instances, which violates the original intention of the class design.
For example:
});
});var b1 = new B();
b1.v.a = 5;
b1.x.a = 5;
console.log(b1.v.a) // The output is 5
console.log(b1.x.a) // The output is 5
console.log(b2.x.a) // The output is 1
console.log(b2.p.a) // If not available, it will prompt that p does not exist
How to solve this problem?
A. The member "member variable" (itself an object) like v is not defined on the prototype chain, but is called in the constructor. At this time, when the object instance is created, it will be in the object's __proto__ Distributed on.
B. Only read-only "member variables" (which themselves are objects) are defined on the prototype chain
The members in the "member variables" (which themselves are objects) defined by C.jpublic are only read-only members. Remember not to assign values, otherwise they will be shared among various instances.