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

Regarding the inheritance method of js, please solve it!

WBOY
Release: 2016-09-21 13:56:40
Original
1023 people have browsed it
<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>
Copy after login

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>
Copy after login
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template