Several inheritance of JavaScript

Source: Internet
Author: User

1. Prototype chain inheritance: The relationship of constructors, prototypes, and instances: each constructor has a prototype object, and the prototype object contains a pointer to the constructor. The instance contains an internal pointer to the prototype object. Confirm the relationship between the prototype and the instance with instanceof.

prototype chain inheritance disadvantages: literal rewrite of the prototype breaks the relationship, uses the prototype of the reference type, and the subtype cannot pass the parameter to the super- type

functionParent () { This. Name= ' Mike '; }    functionChild () { This. age=12; }    //son inherits father (prototype chain)Child.prototype=NewParent ();//Child inherits parent, forms chain through prototype    vartest=NewChild ();    Console.log (Test.age); Console.log (test.name);//Get the inherited property    //grandson continues the prototype chain to inherit the son    functionBrother () { This. weight=60; } Brother.prototype=NewChild ();//inheriting prototype chain inheritance    varBrother=NewBrother (); Console.log (brother.name);//inherits the parent and child, pops up MikeConsole.log (Brother.age);// AConsole.log (brotherinstanceofChild);//tureConsole.log (brotherinstanceofParent);//tureConsole.log (brotherinstanceofObject);//ture
View Code2. Constructors Implement inheritance: also known as forged objects or classic inheritance.

constructors Implement inheritance disadvantages: Although the use of constructors solves the two problems of the inheritance of the prototype chain, but there is no prototype, the reuse is impossible to talk about, so we need the prototype chain + borrowing the constructor pattern.

functionParent (age) { This. name=[' Mike ', ' Jack ', ' Smith '];  This. age=Age ; }    functionChild (age) {Parent.call ( This, age);//point this to the parent, and you can also pass parameters    }    vartest=NewChild (21); Console.log (test.age);// +Console.log (test.name); Test.name.push (' Bill '); Console.log (test.name);//Mike,jack,smith,bill
View Code3. Combination Inheritance: Use the prototype chain to implement the inheritance of the prototype properties and methods, and by borrowing the constructor to implement the inheritance of the instance properties. This means that the function is reused by defining the method on the prototype, and that each implementation has its own properties.

Disadvantages: In any case, a two-time super-type constructor is called, one time when creating a prototype of a subtype, and another in creating a sub-type prototype , the other time is inside the subtype constructor.

functionParent (age) { This. name=[' Mike ', ' Jack ', ' Smith '];  This. age=Age ; } Parent.prototype.run=function(){        return  This. name+ ' is both ' + This. Age; }    functionChild (age) {Parent.call ( This, age);//to the super-type parameter, the second call} child.prototype=NewParent ();//prototype chain inheritance, first call    vartest1=NewChild (21);//Write new Parent (21) also OKConsole.log (Test1.run ());//Mike,jack,smith is both    varTest2=NewChild (22);    Console.log (Test2.age);    Console.log (Test1.age);    Console.log (Test2.run ()); //This allows test1 and test2 to have their own attribute age and can have the Run method
View Code4. prototype Inheritance: Prototypes allow you to create new objects based on existing objects without having to create custom types. it requires that an object be used as the basis for another object.
functionObject (o) {functionF () {}; F.prototype=N; return NewF (); }    varperson={name:' Nicho ', friends:[' Shell ', ' Jim ', ' Lucy ']    }    varAnotherperson =object (person); Anotherperson.name= ' Greg '; AnotherPerson.friends.push (' Rob '); Console.log (anotherperson.friends);//["Shell", "Jim", "Lucy", "Rob"]    varYetanotherperson =object (person); Yetanotherperson.name= ' Linda '; YetAnotherPerson.friends.push (' Barbie '); Console.log (yetanotherperson.friends);//["Shell", "Jim", "Lucy", "Rob", "Barbie"]Console.log (person.friends);//["Shell", "Jim", "Lucy", "Rob", "Barbie"]
View Code

ECMASCRIPT5 normalized the prototype inheritance by adding the Object.create () method, which receives two parameters: an object to be used as a prototype for the new object and (optionally) an object that defines the properties for the new object.

varPerson2={name:' Nicho ', friends:[' Shell ', ' Jim ', ' Lucy ']    }; varAnop2=object.create (Person2); Anop2.name= "Greg"; AnoP2.friends.push (' Rob '); Console.log (anop2.friends);//["Shell", "Jim", "Lucy", "Rob"]    varYetp2=object.create (Person2); Yetp2.name= "Linda"; YetP2.friends.push (' Barbie '); Console.log (yetp2.friends);//["Shell", "Jim", "Lucy", "Rob", "Barbie"]Console.log (person2.friends);//["Shell", "Jim", "Lucy", "Rob", "Barbie"]    /*any property specified in this manner overrides the same name property on the prototype object. */    varthreep=object.create (person,{name:{value:' Red '}    }); Console.log (threep.name);//Red, if no name is in Threep, outputs the name value in Person2 Nicho
View Code5. Parasitic inheritance: The idea is similar to a parasitic constructor and a factory pattern, which is to create a function that encapsulates the inheritance process internally, which in some way enhances the object, and finally returns the object as if it did all the work.
functionObject (o) {functionF () {}; F.prototype=o; return NewF ();    }; functionCreateanother (o) {varCl=object (o); Cl.sayhi=function() {Console.log (' Hi '); }        returncl;    }; varperson={name:' Nick ', friends:[' Shelby ', ' Court ', ' van ']    }    varanotherperson=Createanother (person); Anotherperson.sayhi ();//HiConsole.log (Anotherperson.name);//NickConsole.log (Anotherperson.friends);//["Shelby", "court", "Van"]    /*The code in this example returns a new object--anotherperson based on person. The new object not only has all the properties and methods of person, but also has its own sayhi () method*/
View Code

Parasitic combined inheritance: in any case, the two-time super-type constructor is called, one time when creating a prototype of a subtype, another when creating a prototype of a subtype, and another within the subtype constructor, which eventually contains all the instance properties of the superclass object. We had to override these properties when we called the subtype constructor. Therefore, parasitic combined inheritance occurs.

6. Parasitic combined inheritance: the use of constructors to inherit attributes, through the formation of the prototype chain to inherit the method. Basic idea: You don't have to call a super-type constructor to specify a prototype for a subtype. Essentially, a parasitic inheritance is used to inherit a super-type prototype, and then the result is assigned to the prototype of the subtype.
functionsupertype (name) { This. name=name;  This. colors=[' red ', ' blue ', ' green ']; } SuperType.prototype.sayName=function() {Console.log ( This. Name); }    functionSubtype (name,age) {Supertype.call ( This, name);  This. age=Age ; }    functionObject (o) {functionF () {}; F.prototype=N; return NewF ();    }; /*Inheritprototype The first step in this function is to create a copy of the super-type prototype. The second step is to add the constructor property to the created copy, * To compensate for the default constructor property lost due to rewriting the prototype, and the third to assign the newly created object (copy) to the child type's prototype*/    functionInheritprototype (subtype,supertype) {varPrototype=object (Supertype.prototype);//Creating ObjectsPrototype.constructor=subtype;//Enhanced ObjectsSubtype.prototype=prototype;//Specifying Objects} inheritprototype (Subtype,supertype); SubType.prototype.sayAge=function() {Console.log ( This. Age); }    varp=NewSubtype (' Xiaoli ', 24);    Console.log (P.sayname ());    Console.log (P.sayage ()); Console.log (p.colors)
View Code

The advantage of this method is that only once the parent class Supertype constructor is called, and therefore avoids creating unnecessary unnecessary properties on the Subtype.prototype. At the same time, the prototype chain can remain unchanged, and the normal use of instanceof and isprototypeof ();



Several inheritance of JavaScript

Related Article

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.