Home  >  Article  >  Backend Development  >  Regarding the inheritance method of js, please solve it!

Regarding the inheritance method of js, please solve it!

WBOY
WBOYOriginal
2016-09-21 13:56:40970browse
<code>function person(name,age){
    this.name = name;
    this.age = age;
}
person.prototype.say = function(){
    console.log(this.name+":"+this.age);
}

function superman(name,age){
    person.call(this,name,age);
}
superman.prototype = new person();

var s = new superman('superman',29);
</code>

I saw this inheritance method in a book and said it was perfect, but I don’t think so because its superman.prototype = new person();This sentence will add the instance attributes of the parent class to the child class. On the prototype, although person.call(this, name, age); has obtained the instance attributes of the parent class, it feels like this pollutes the prototype of the subclass. How to break it?

Okay, the problem is solved, using parasitic combined inheritance can solve this problem

<code>function object(obj){
 function F(){}
 F.prototype = obj;
 return new F();
}

function inheritProtoType(SuperType,SubType){
     var prototype = object(SuperType.prototype);
     prototype.constructor = SubType;
     SubType.prototype = prototype;
}

function SuperType(){
    this.name = 'yuhualingfeng';
    this.friends = ['David','Bob','Lucy'];
}
SuperType.prototype.saySuperName = function(){
    console.log(this.name);
};

function SubType(){
    SuperType.call(this);
    this.age = 30;
}
inheritProtoType(SuperType,SubType);

SubType.prototype.saySubName = function(){
    console.log(this.name);
};

var subType = new SubType();
</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn