Thoughts on JavaScript combination inheritance

Source: Internet
Author: User

Today, when I read the "JavaScript advanced programming" book about the combination inheritance mode, there is such a Demo program:


SubType. prototype = new SuperType () raises a question. Isn't the purpose of this statement to point the child Type prototype to the parent Type prototype instance? Why not write SubType. prototype = SuperType. prototype directly? Why do we have to create a new one?

After careful consideration, I made the following modifications to the Demo and figured out the reasons for doing so:


The prompt displayed after running instance2.sayAge is undefined. That is to say, when we add a method sayAge to be held by the Child type, we accidentally contaminated the parent type, so that the parent type also has the sayAge method, and the parent type does not have the age attribute at all, of course, this attribute will be prompted undefined. The reason for these strange phenomena is that SubType is directly used. prototype = SuperType. prototype. If you replace this sentence with SubType. if prototype = new SuperType () is used to call the sayAge method, an error will be executed because the parent type does not have this method at this time (there is no quilt type pollution ), so it is very scientific and reasonable to use new.

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.