Reference Nanyi's article: http://javascript.ruanyifeng.com/oop/inheritance.html#toc4
functionShape () { This. x = 0; This. y = 0;} Shape.prototype.move=function(x, y) { This. x + =x; This. Y + =y; Console.info (' Shape moved. ');};functionRectangle () {Shape.call ( This);//calling the parent class constructor}//Another way of writingfunctionRectangle () { This. Base =Shape; This. Base ();}//subclass inherits methods of parent classRectangle.prototype =object.create (Shape.prototype); Rectangle.prototype.constructor=Rectangle;varRect =NewRectangle (); RectinstanceofRectangle//trueRectinstanceofShape//trueRect.move (1, 1)//' Shape moved. '
The above code indicates that the inheritance of the constructor is divided into two parts, one of which is the constructor of the child class calling the parent class, and the other part is the prototype of the subclass that points to the parent class.
In the code above, the subclass inherits the parent class as a whole. Sometimes, you only need the inheritance of a single method, and you can use the following notation.
function () { ClassA.prototype.print.call (this); // some code}
In the code above, B
the subclass's print
method calls the parent class A
's method first print
and then deploys its own code. This is tantamount to inheriting the method of the parent class A
print
.
How the JavaScript Neutron class inherits the parent class