JavaScript Object-Oriented Programming (6) Inheritance using prototype chain, javascript object-oriented
Inheritance is one of the object-oriented features, and the main purpose of inheritance is to reuse. Sub-classes can reuse attributes or behaviors of parent classes, greatly simplifying sub-classes and avoiding repeated definitions.
Inherited features 1. attributes and methods of parent objects of sub-objects
Inheritance Feature 2: The Sub-object "is a" parent object and has the "is-a" feature,
If a person is an animal, then a person is a sub-class of an animal, embodied in an object. A person must have a reference pointing to an animal instance.
The prototype of the subclass points to an instance of the parent class to complete inheritance, because the instance of the subclass has the attributes and behaviors of the parent class instance.
In Java, the subclass instance has the super keyword pointing to the parent class instance. In terms of inheritance, all object-oriented languages are similar.
// Shape function Shape () {this. name = 'shape'; this. toString = function () {return this. name ;}}// 2d shape function TwoDShape () {this. name = '2d shape';} // Triangle function Triangle (side, height) {this. name = 'angle '; this. side = side; this. height = height; this. getArea = function () {return this. side * this. height/2 ;};/// inherited feature 1. the sub-object has attributes and methods of the parent object TwoDShape. prototype = new Shape (); Triangle. prototype = new TwoDShape (); // fixed TwoDShape. prototype. constructor = TwoDShape; Triangle. prototype. constructor = Triangle; var my = new Triangle (5, 10); alert (my. toString (); // you do not have the toString method and inherit from alert (my. constructor);/* inherited Feature 2: Sub-object "is a" parent object, with the "is-a" feature. If a person is an animal, then a person is a subclass of an animal, embodied in objects, a person must have a reference pointing to an animal instance */alert (my instanceof TwoDShape); // has the inherited feature alert (my instanceof Shape );