1. Prototype chain
- Using prototypes to let one reference class inherit another property and method of a reference type
1 functionsupertype () {2 This. property =true;3 }4 5SuperType.prototype.getSuperValue =function () {6 return This. property;7 }8 9 functionsubtype () {Ten This. Subproperty =false; One } A -Subtype.prototype =Newsupertype (); -SubType.prototype.getSubValue =function () { the return This. Subproperty; - } - - varInstance =Newsubtype (); +Console.log (Instance.getsupervalue ());
2. Borrowing constructors
- Calls the superclass's constructor inside the constructor of the subclass, using the call () or the Apply () function.
1 functionsupertype (name) {2 This. Name =name;3 }4 5 functionsubtype () {6 //inherits the superclass, and also passes the parameters7Supertype.call ( This, ' Nick ');8 This. Age = 29;9 }Ten One varInstance =Newsubtype (); AConsole.log (Instance.name);
- Methods are created in the constructor and cannot be reused.
3. Combining inheritance
- Combining the advantages of inheriting from a prototype chain and borrowing a constructor, you can have two instances with different attributes, and you can have a common approach
1 functionsupertype (name) {2 This. Name =name;3 This. color = ["Red", "blue"];4 }5 6SuperType.prototype.sayName =function () {7Console.lgo ( This. Name);8 }9 Ten functionsubtype (name, age) { OneSupertype.call ( This, name); A This. Age =Age ; - } - //Inheritance theSubtype.prototype =Newsupertype (); -SubType.prototype.sayAge =function () { -Console.log ( This. age); - } + - varInstance =NewSubtype (' Nick ', 29); +Instance.sayage ();
4. prototype-Type Inheritance
1 functionObject (o) {2 functionF () {};3F.prototype =o;4 return NewF ();5 }6 //This method is similar to the object.create () function, but the latter is compatible with mainstream browsers only7 varperson = {8Name: "Nick",9Age:29Ten } One A varanother =object.create (person); -Console.log (Another.name);
5. Parasitic
Six ways that Javascript inherits