Prototype chain is the most important way to inherit,
Principle: Each class (constructor, JS function) has a prototype attribute (prototype) point to a prototype object, the prototype object has a constructor (constructor), it refers back to function, is a circular reference, Each instance of the class also has a prototype property (code unreachable, called _proto_), which points to the same object as the constructor prototype, which is a common prototype object for all instances of the same class, to implement two types of inheritance, which is to point a prototype of one type to an instance of another type. Instead of specifying the original default prototype object, this creates a prototype chain
Subclasses can get all the properties and methods of the superclass through the prototype chain, thus implementing the inheritance
Instance:
function BaseClass () {this.basename = ' baseclass ';}
BaseClass.prototype.getbaseClassName = function () {return this.basename};
function ChildClass () {this.childname = ' childclass ';}
Childclass.prototype = new BaseClass ();
ChildClass.prototype.getchildClassName = function () {this.childname;}
var instanse = new ChildClass ();
Instanse.getbaseclassname ();
The prototype (_proto_) property of ChildClass (and its instance) is not pointing to the default prototype object, but rather an instance of BaseClass, which also has a property (_proto_) that points to the prototype object of BaseClass , the process of locating the BaseName property on the instance instanse of ChildClass is this:
First in the instanse itself, but not found, and then into its prototype object (_proto_ attribute, at this time is the instance of BaseClass, no longer the default prototype object) is still not found, then into the BaseClass instance of the prototype object (_proto_ property, On the default prototype object), finally found, returns the execution result of this method,
The prototype object of a class is shared by all instances, which creates a problem that changes to the properties and methods of the prototype object (the parent class instance) will affect all instances, whether created or created
function BaseClass () {this. Colors = [' Bule ', ' Red ']; }
function ChildClass () {}
Childclass.prototype = new BaseClass ();
var instanse1 = new ChildClass ();
var instanse2 = new ChildClass ();
Modify properties inherited from the parent class on this instance
Instanse2. Colors.push (' green ');
var instanse3 = new ChildClass ();
View Colors property values for individual instances
alert (instanse1.colors);//red,blue,green
alert (instanse2.colors);//red,blue,green
alert (instanse3.colors);//red,blue,green
Visible for either instance, if the inherited property value is modified, the instance that is created at any time will be affected
In addition, if there are too many levels of inheritance, the least efficient call to the topmost layer
JavaScript class Inheritance Series II (prototype chain)