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.