This time I will bring you js parasitic combined type inheritance Detailed explanation of use, what are the precautions for using js parasitic combined type inheritance, the following is a practical case, one Get up and take a look.
Combined inheritance:
function Person( uName ){ this.skills = [ 'php', 'javascript' ]; this.userName = uName; } Person.prototype.showUserName = function(){ return this.userName; } function Teacher ( uName ){ Person.call( this, uName ); } Teacher.prototype = new Person(); var oT1 = new Teacher( 'ghostwu' ); oT1.skills.push( 'linux' ); var oT2 = new Teacher( 'ghostwu' ); console.log( oT2.skills ); //php,javascript console.log( oT2.showUserName() ); //ghostwu
There is a disadvantage of combined inheritance. The constructor of the parent class will be called twice.
Line 11, sets the subclass prototype object (prototype), and calls the first
Line 9, when instantiating the object, call
again The purpose of the constructor is to copy attributes. Line 9 is definitely indispensable. The purpose of line 11 is to obtain the method on the parent class prototype object (prototype). Based on this purpose, is there any Other methods
Can it be done? Can we get the methods on the prototype object of the parent class without instantiating the parent class constructor? Of course, we can use parasitic inheritance to get the methods on the parent class prototype object
function Person( uName ){ this.skills = [ 'php', 'javascript' ]; this.userName = uName; } Person.prototype.showUserName = function(){ return this.userName; } function Teacher ( uName ){ Person.call( this, uName ); } function object( o ){ var G = function(){}; G.prototype = o; return new G(); } function inheritPrototype( subObj, superObj ){ var proObj = object( superObj.prototype ); //复制父类superObj的原型对象 proObj.constructor = subObj; //constructor指向子类构造函数 subObj.prototype = proObj; //再把这个对象给子类的原型对象 } inheritPrototype( Teacher, Person ); var oT1 = new Teacher( 'ghostwu' ); oT1.skills.push( 'linux' ); var oT2 = new Teacher( 'ghostwu' ); console.log( oT2.skills ); //php,javascript console.log( oT2.showUserName() ); //ghostwu
In fact, to put it bluntly, parasitic combined inheritance is a prototype object that borrows a constructor and is equivalent to a shallow copy of the parent class
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website !
Recommended reading:
The above is the detailed content of Detailed explanation of the use of parasitic combined inheritance in js. For more information, please follow other related articles on the PHP Chinese website!