Prototyping and inheriting learning notes 4

Source: Internet
Author: User

After the previous study, we can finally realize the inheritance of the language that cannot realize the interface inheritance, in order to better object-oriented ...

    Prototype chain inheritance

This prototype chain we quoted in the previous section, the basic idea of using it to implement inheritance is to use a prototype to refer to another reference type's properties and methods. That is, all properties and methods (examples of this function) of a function (in narrow sense) are assigned to the prototype of another function, so that an instance of a function can invoke all the properties of another function through a layer of __proto__ prototypes.

A bit of a detour, simply put, is to assign the instance of the superclass to the prototype of the subclass. Look at an example:

1 functionsupertype () {2      This. Name = ' Super ';3 };4SuperType.prototype.getName =function() {5Console.log ( This. Name);6 };7 8 functionsubtype () {9      This. Age = 10;Ten }; OneSubtype.prototype=Newsupertype (); ASuperType.prototype.getAge =function() { -     return  This. Age; - }; the  - varSub =Newsubtype (); -Sub.getname ();//Super

If the 11th behavior assigns the instance of Supertype to the prototype of subtype, then the subtype Instantiation object sub can access the parent class's Method GetName (), because this method already exists on the sub's prototype.

But the prototype chain is not without its own problem, the main problem is that the prototype property that contains the reference type value is shared by all instances. The prototype will actually become an instance of another type, so the original instance attribute becomes the prototype attribute now.

1 functionsupertype () {2      This. family=[' brother ', ' sister '];3 };4 5 functionsubtype () {};6Subtype.prototype =Newsupertype ();7 8 varobj1=Newsubtype ();9Obj1.family.push (' cousin ')TenConsole.log (obj1.family);//["Brother", "sister", "cousin"] One  A varObj2=Newsubtype (); -Console.log (obj2.family);//["Brother", "sister", "cousin"]

The 6th line of Supertype is assigned to subtype's prototype, The equivalent of creating a SubType.prototype.family property, the result is that subtype all instances have shared this property, resulting in obj1 modification of this property on the OBJ2 also reflected.

    Borrowing constructors

The idea of this approach is to call the superclass constructor inside the subclass constructor, that is, by calling () or the Apply () method to invoke the Supertype constructor in the context of the newly created subtype instance, and then the newly created object is in the borrowed child, A child who appears to be subtype, is essentially a child of supertype, and of course can inherit all the inheritable properties and methods of two people.

1 functionsupertype () {2      This. Family = [' brother ', ' sister '];3 };4 functionsubtype () {5Supertype.call ( This);6 };7 varObj1 =Newsubtype ();8Obj1.family.push (' cousin ');9Console.log (obj1.family);//["Brother", "sister", "cousin"]Ten  One varObj2 =Newsubtype (); AConsole.log (obj2.family);//["Brother", "sister"]

As on the 7th row of the instantiation of the obj1, call subtype's constructor, and subtype's inner actually executes the supertype constructor, therefore implements the inheritance, and Obj2 will call the Supertype constructor again at the time of instantiation. To get a SuperType.prototype.family again, the call () and the Apply () function are all arguments, which solves the problem of the prototype chain inheritance. No reference is shown here.

But it's OK to borrow the constructor, of course not, the problem with the constructor pattern used to create the object is the same--all the methods have to be written in the constructor, so that each time the method is instantiated, the consequence is that the function cannot be reused and does not conform to object-oriented thinking.

    Combining inheritance

In fact, this approach is to make the above two ways, using the prototype chain to implement the prototype properties and methods of inheritance, using constructors to implement the inheritance of instance properties, so as to ensure that the function of reuse, but also to ensure that each instance has its own unique properties.

1 functionsupertype (name) {2      This. name=name;3      This. color=[' red ', ' blue ']4 };5Supertype.prototype.sayname=function  () {6Console.log ( This. Name);7 };8 functionsubtype (name) {9Supertype.call ( This, name);Ten }; OneSubtype.prototype=Newsupertype (); ASubType.prototype.constructor =subtype; -  - varObj1 =NewSubtype (' James '); theObj1.color.push (' Black '); -Console.log (Obj1.color);//[' Red ', ' blue ', ' black '] -Obj1.sayname ();//James -  + varObj2 =NewSubtype (' Wade '); -Console.log (Obj2.color);//[' Red ', ' blue '] +Obj2.sayname ();//Wade

The 9th Behavior borrows the constructor, guarantees that the instantiation time will take a new name and color each time, but the prototype method can realize the method sharing, guarantees the reusability, the 12th line belongs to the prototype constructs the redirection, Because all of subtype's properties are from supertype in 11 rows, which naturally includes this constructor. In a nutshell: Prototype inheritance is too passionate about sharing, sharing what should be shared (methods) and non-shared (character-specific instance attributes), and the constructor method is too passionate about individuality and assigns all that should be shared. This combination of inheritance has become the most commonly used inheritance model, combining their merits.

    Prototype inheritance

In fact, the upper part of the combined inheritance of the constructor process is encapsulated, first look at the code:

1 function Object (o) {2     function F () {}; 3     F.prototype=o; 4     return New F (); 5 }

First of all, this temporary transfer function, inside the object function, passed in a target, the object as the constructor of the prototype, and finally return the temporary function of the new instance, the new instance has all the properties and methods of the object O.

But this f.prototype=o; The statement will share this object o, and the problem with the prototype chain inheritance is the same, and then we have to say one of our previous old friend Object.create () method, this method accepts two parameters, The first parameter is used as the object for the new object prototype and optionally an object that defines additional properties for the new object. In the case where only one parameter is passed, this method is the same as the above object. So there is no problem of sharing property with reference type values, but it can provide a perfect solution to look down.

Parasitic inheritance

This method creates a temporary transit function that encapsulates the inheritance process, and returns the object after doing something inside the function, as follows:

    Parasitic combined inheritance

Discussed before, the combination of inheritance is the most common one of the inheritance model, but also has its own problem, he will call two times in any case the constructor, go back to the top, the first time in the 11th line to create a prototype of the subtype, the second time in the 9th row subtype of the interior of the constructor, So now the perfect solution comes out, that's the parasitic combined inheritance:

This approach essentially inherits the super-type prototype with parasitic inheritance, and then assigns the result to the prototype of the subtype, which is equivalent to the other operation of Subtype.prototype=new super (). The first is a temporary transfer function:

1 function Inheritprototype (subtype,supertype) {2     var prototype = object.create (supertype). prototype; 3     Prototype.constructor = subtype; 4     Subtype.prototype=prototype; 5 };

Use the call of this function instead of the combination of Subtype.prototype=new Super () in the inheritance, you can get:

1 functionInheritprototype (subtype,supertype) {2      varPrototype =object.create (supertype). prototype;3Prototype.constructor =subtype;4Subtype.prototype=prototype;5  };6 7 functionsupertype (name) {8      This. Name =name;9      This. color = [' Blue ', ' red '];Ten }; OneSupertype.prototype.sayname=function  () { AConsole.log ( This. Name); - }; - functionsubtype (name) { theSupertype.call ( This, name); - }; - Inheritprototype (subtype,supertype); - varobj =NewSubtype (' Success '); +Obj.sayname ();//Success -Obj.color.push (' Black '); +Console.log (Obj.color)//["Blue", "Red", "black"] A  at varobj =NewSubtype (' Thanks '); -Obj.sayname ();//Thanks -Console.log (Obj.color)//["Blue", "Red"]

To this basic is also the end, the main idea is to recognize the dynamic nature of prototype and the relationship with constructor, in fact, the above code can be simplified again, that is, the transfer function is opened to write, how to change it, in fact, previously said:

1 functionsupertype (name) {2      This. Name =name;3      This. color = [' Blue ', ' red '];4 };5Supertype.prototype.sayname=function  () {6Console.log ( This. Name);7 };8 functionsubtype (name) {9Supertype.call ( This, name);Ten }; OneSubtype.prototype =object.create (supertype). prototype; ASubType.prototype.constructor =subtype; - varobj =NewSubtype (' Success '); -Obj.sayname ();//Success theObj.color.push (' Black '); -Console.log (Obj.color)//["Blue", "Red", "black"] -  - varobj =NewSubtype (' Thanks '); +Obj.sayname ();//Thanks -Console.log (Obj.color)//["Blue", "Red"]

In the final analysis, this key point is the Object.create () function, about which the function is said in the prototype inheritance.

Recognizing that a function is an object, an object's __proto__ prototype, a function's prototype property, and the rules between them, it is relatively easy to understand, thanks to accompany, written to be more difficult than imagined, originally thought that the 1-day workload actually wrote must put together before and after the series, Think more than their own simple understanding, hope to bring you a little something to want.

Prototyping and inheriting learning notes 4

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.