Javascript development notes: incomplete inheritance and incomplete javascript
Javascript inheritance is very different from standard oop inheritance. Javascript inheritance uses prototype chain technology,
Each class puts "member variables" and "member functions" on prototype, and Js ++ links them through superclass.
C. prototype. superclass = C. superclass = P. prototype;
When var c = new C (), c. _ proto _ = C. prototype;
When c accesses the "member variable", if _ proto _ cannot be obtained, it will go to C. prototype lookup. If no prototype exists, the prototype of the parent class will be searched. Because only _ proto _ is allocated when the object is created (each object is allocated independently ), others are allocated when the definition is made (each object is shared). At this time, if you access C. in prototype, when the "member variable" is an object, the "member variable" itself is not modified, but the member of the "member variable" object is modified, members of the modified "member variables" object will be shared by all object instances, which violates the original intention of class design.
For example:
'Package '. j (function () {'class '. j (function () {jpublic ({v: {a: 1}); jprivate ({p: {a: 1}); jprotected ({x: {: 1 }}) ;}); 'class B extends '. j (function () {}) ;}); var b1 = new B (); b1.v. a = 5; b1.x. a = 5; var b2 = new B (); console. log (b1.v. a) // The output is 5console. log (b1.x. a) // The output is 5console. log (b2.v. a) // The output is also 5, which is not the expected 1console. log (b2.x. a) // The output is 1console. log (b2.p. a) // unavailable, p does not exist
How can this problem be solved?
A. the member "member variable" such as "v" (which is an object itself) is not defined on the prototype chain, but called in the constructor. At this time, when an object instance is created, it will be allocated on _ proto _ of the object.
Js ++ provides similar methods. As long as the "member variables" or "member functions" defined in jprivate are allocated to the _ proto _ of the object, only this instance is available. The "member variable" defined in jprotected (which is an object itself) is also allocated to the _ proto _ of the object, and only inherits its availability,
B. The prototype chain only defines read-only "member variables" (the object itself)
C. The members in the "member variable" defined by jpublic (which is an object) are only read-only members. Do not assign values. Otherwise, they will be shared among instances.