JavaScript is not a purely object-oriented language, so there is no explicit way to inherit, but there are some ways to emulate inheritance. This article summarizes the common JavaScript inheritance simulation methods
1, Object inheritance
//Parent ClassfunctionPerson (name,age) { This. Name =name; This. Age =Age ;}; Person.prototype.height= "170cm";//sub-classfunctionBoy () { This. Speak =function() {alert ("I am a subclass"); }; };//How to inheritBoy.prototype =NewPerson ("Xiaoming", "20");//TestvarBoy =NewBoy (); Boy.speak (); //I'm a sub-categoryalert (boy.name);//xiaomingalert (boy.age);// -alert (boy.height);//170cm
This approach is inherited by setting the prototype object of the subclass to the instance object of the parent class
The advantage of this method is that it inherits both the Class property of the parent class and the property in the parent prototype object.
The disadvantage is that if you need to pass parameters when you create a subclass object, you can only use the parent class to receive parameters, are less flexible, and are not syntactically object-oriented
2, class inheritance
//Parent ClassfunctionPerson (name,age) { This. Name =name; This. Age =Age ;} Person.prototype.height= "170cm";//subclasses and Inheritance methodsfunctionBoy (name,age) {Person.call ( This, Name,age); This. Speak =function() {alert ("I am a subclass"); }}//TestvarBoy =NewBoy ("Xiaoming", "20"); Boy.speak (); //I'm a sub-categoryalert (boy.name);//xiaomingalert (boy.age);// -alert (boy.height);//undefined
This kind of inheritance actually means calling the parent class function through call in the subclass function
The advantage is that when you create a subclass, the pass-through parameter does not need to be passed to the parent class and is flexible, with the disadvantage of inheriting only the class property of the parent class and not inheriting the property in the parent class's prototype object
3, Mixed inheritance
//Parent ClassfunctionPerson (name,age) { This. Name =name; This. Age =Age ;} Person.prototype.height= "170cm";//subclass and Inheritance methodfunctionBoy (name,age) {Person.call ( This, Name,age); This. Speak =function() {alert ("I am a subclass"); }}boy.prototype=NewPerson ();//TestvarBoy =NewBoy ("Xiaoming", "20"); Boy.speak (); //I'm a sub-categoryalert (boy.name);//xiaomingalert (boy.age);// -alert (boy.height);//170cm
This kind of inheritance is actually the combination of the two ways, so there is a second way of flexibility, and the first way of comprehensive
Boy.prototype = new Person (); There is no parameter passed in this sentence, which inherits the attributes from the parent class's prototype object, and the call method inherits the class property of the parent class.
Three ways that JavaScript inherits