About the js inheritance method, solve it!

Source: Internet
Author: User
{Code ...} this inheritance method is perfect in the book, but I don't think it is because of his superman. prototypenewperson (); adds the instance attribute of the parent class to the prototype of the subclass. call (this, name, age); has obtained the parent class...
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);

This inheritance method is perfect in the book, but I don't think it's because of hissuperman.prototype = new person();This statement will add the instance attributes of the parent class to the prototype of the subclass.person.call(this,name,age);I have obtained the instance attribute of the parent class, but it seems that the prototype of the subclass is contaminated. how can this problem be solved?

Okay, the problem is solved. the problem can be solved through parasitic combined inheritance.
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();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.