Constructor (class) inheritance and experiment

Class inheritance: the way to inherit from constructors (classes)

Class: JS is a class without a concept, a class that treats constructors in JS as examples

funcTIon Aaa () { // parent class this .name = '小明' ; } Aaa.prototype.showName = funcTIon () { alert( this .name ); }; funcTIon Bbb () { //subclass } Bbb.prototype = new Aaa(); //This is called class inheritance var b1= new Bbb(); b1.showName(); //小明 ert(b1.name); //小明(also a layer search)

The following figure clearly shows the above relationship

这里写图片描述

Question 1: But the above inheritance is problematic. If we don't believe, we will do an experiment. Continue to add code based on the above code

Alert( b1 .constructor ) ;

pop up

funcTIon Aaa () { //Parent class this .name = '小明' ; }

So you should add a sentence to correct the problem.

Bbb.prototype = new Aaa(); //This is called class inheritance Bbb.prototype constructor = Bbb ; //fix pointing problem

Question 2: Make the above code slightly modified

function Aaa () {// parent this .name = [1, 2, 3];} Aaa.prototype.showName = function () {alert (this .name);}; function Bbb () {// subclass } Bbb.prototype = new Aaa(); Bbb.prototype.constructor = Bbb; //Fixed to the problem var b1 = new Bbb(); b1.name.push( 4 ); var b2 = new Bbb(); alert( B2.name ); //[1,2,3,4]

Analysis, b1, b2 are different objects, but the above affect each other, so there is a problem. Because both find the name under new Aaa(), it is a thing, so it will affect each other.
Can be corrected like this, as shown below

function Aaa () {// parent this .name = [1, 2, 3];} Aaa.prototype.showName = function () {alert (this .name);}; function Bbb () {// subclass Aaa.call( this ); //1 here implements the transfer attribute } var F = function () { }; F.prototype = Aaa.prototype; Bbb.prototype = new F(); //From the picture below See that there is only a way to pass the method, there is no way to pass the property Bbb.prototype.constructor = Bbb; // fix the problem var b1 = new Bbb(); b1.name.push( 4 ); var b2 = new Bbb( ); alert( b2.name ); //[1,2,3,4]

这里写图片描述

Plastic Capillary Pressure Gauge

Plastic Capillary Pressure Gauge,Mini-Sized Capillary Manometer,D28 Plastic Tube Pressure Gauge,Pipe Manometer

ZHOUSHAN JIAERLING METER CO.,LTD , https://www.zsjrlmeter.com