There is a big difference between the inheritance of JavaScript and the standard OOP inheritance. The inheritance of JavaScript uses the primary chain technology. Each class will put "member variables" and "member functions" on Prototype. Get up, that is, c.prototype.superclass = c.superclass = p.prototype;
When var c = new c (), C .__ Proto__ = C.prototype;
When C visits "member variables", if __proto__ cannot be obtained, you will go to c.prototype to find it. If it does not exist, it will be found in the parent of the parent. (Each object is independently allocated), and others are allocated during definition (each object is shared). At this time, if "member variables" in C.Prototype are accessible When a member of the "member variable" object is modified, the members of the "member variables" objects modified will be shared by all object instances, which violates the original intention of class design.
For example:
Copy code code as follows:
'package'.j (function () {
'Class a'.j (function () {
jpublic ({{{{
V: {A: 1}
});
jprivate ({{
p: {A: 1}
});
jprotect ({{
x: {a: 1}
});
});
'Class B EXTENDS A'.j (Function () {
});
});
var b1 = new b ();
b1.va = 5;
b1.xa = 5;
var b2 = new b ();
console.log (b1.va) // output as 5
console.log (b1.xa) // output as 5
Console.log (B2.VA) // Output is also 5, not expected 1
console.log (b2.xa) // output as 1
console.log (b2.pa) // Unsable, it will prompt P without existence
How to solve this problem?
A. The "member variable" (itself is an object in itself) such as V is not defined on the original chain, but is called in the constructor. At this time, when creating an object instance, it will be assigned on the object's __proto__.
JS ++ provides a similar method, as long as the "member variable" or "member function" defined in JPRIVATE is allocated on the outer __proto__, and only this instance is available. Object) will also be assigned to the __proto__
B. The "member variable" only reads only read on the prototype chain (it is an object in itself)
The members of the "member variables" (itself are objects) defined by C.JPUBLIC, just read only members, remember not to be assigned, otherwise it will be shared in various instances.