Javascript tutorial of the incomplete inheritance of of js prototype chain

  • 2020-03-30 01:19:13
  • OfStack

Javascript inheritance is very different from the standard oop inheritance. Javascript inheritance is a prototype chain technology. Each class will put "member variables" and "member functions" on the prototype.
When var c = new c (), c.
When c access "member variables", if you are unable to obtain __proto__, would be to C.p rototype search, if there is no again, and will to the parent class prototype lookup, because only __proto__ is object creation time allocation (distribution of each object independent), when all else is to define the distribution (each object sharing), at this point, if the access C.p rototype "member variable is an object, not modify" member variables "itself, but to modify" member variables "members of the object, The members of the modified "member variable" object are Shared by all object instances, which defeats the purpose of the class design.
Such as:

'package'.j(function () {
        'class A'.j(function () {
                v:{a: 1}
        'class B extends A'.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 of 5
console.log(b1.x.a) //The output of 5
console.log(b2.v.a) //The output is also 5, not the expected 1
console.log(b2.x.a) //The output is 1
console.log(b2.p.a) //It's not available, it says p doesn't exist

How to solve this problem?
A. Call A member "member variable" such as v (which is itself an object) not on the prototype chain, but in the constructor, where the object instance is created, then on the object's s s.

Js++ provides a similar approach, as long as defined in jprivate "member variable" or "member function" __proto__ is assigned to the object, and only this instance is available, jprotected defined in the "member variables" (object itself) will also be assigned to the object's __proto__, and only succeed to the available,

B. Only read-only "member variables" (which themselves are objects) are defined on the stereotype chain

C.jpublic defines a member of a "member variable" (which is itself an object) that is a read-only member and must not be assigned, or it will be Shared across instances.

Related articles: