JavaScript Advanced Programming Reading notes
The book inherits several kinds of implementations, two of which are more reliable.
1 Combination Inheritance
//Parent ConstructorfunctionSuper (name) { This. Name =name; This. colors = [' black ', ' red '];}
Super.prototype.getName=function() { return This. Name;
Child ConstructorsfunctionSub (name, age) {Super.call ( This, name); This. Age =Age ;}
By modifying the sub's prototype to a super instance, you can inherit the properties and methods in the Super.prototype,
The problem with this is that the name and colors attributes are also added to the Sub.prototype, which is not visible to the instance.
Because the call to new Sub () generates an instance, name and colors are added as instance properties Sub.prototype=NewSuper (); Sub.prototype.getAge=function(){ return This. Age;
When Sub.prototype is modified earlier, it causesSub.prototype.constructor point to Super, so change it back
=
var New Sub (' Mengxb ', 28);
2 Parasitic combined inheritance
functionObject (o) {functionF () {}; F.prototype=o; return NewF ();}functionInheritprototype (Sub, super) {varPrototype =Object (Super.prototype); Sub.prototype=prototype; Sub.prototype.construtor=Sub;}functionSuper (name) { This. Name =name; This. colors = [' black ', ' red '];} Super.prototype.getName=function() { return This. Name;functionSub (name, age) {Super.call ( This, name); This. Age =Age ;} Inheritprototype (Sub, Super); Sub.prototype.getAge=function(){ return This. Age;
JavaScript Inheritance Implementation