Graphical JavaScript inheritance

Source: Internet
Author: User
Tags hasownproperty

JavaScript, as an object-oriented language, can implement inheritance is necessary, but because there is no concept of the class (do not know whether it is rigorous, but in JS all classes are object simulation) so in JavaScript inheritance is also different from other object-oriented language. Perhaps a lot of beginners know how to implement JS inheritance, but the principle of implementing inheritance is confused. So, today we're going to illustrate JavaScript inheritance. (Because the inheritance has knowledge about the prototype, so I hope you have a certain understanding of the prototype recommended reading: Understanding JavaScript prototype comb JavaScript prototype overall idea).

Let's start by looking at the various ways JavaScript inherits and how they work.

1. Default mode

  1. 1        /**2 * [default inheritance mode]3          */4         functionParent (name) {5              This. Name = Name | | ' Adam ';6         }7         varParent =NewParent ();8Parent.prototype.say =function() {9             return  This. Name;Ten         }; One         functionChild (name) {} AChild.prototype =NewParent (); -         varKid =NewChild (); -Console.log (Kid.hasownproperty (' name '));//false theConsole.log (Parent.hasownproperty (' name '));//true -Console.log (Kid.say ());//Adam -Kid.name = ' Lili '; -Console.log (Kid.say ());//Lili +Console.log (Parent.say ());//Adam

    The above code implementation inherits the 12th line of Child.prototype = new parent (); By this code, the child's prototype becomes an instance of the parent.

As you can see, the parent is a constructor, and there is a Parent.prototype object with an say () method inside the object (not one of the prototype other property methods listed here). There is also a child constructor, we let the object instantiated by the parent as CIHLD prototype (after all prototype is also an object, so our atmosphere not). In fact, to be more convenient to understand, this sentence can be changed to var parent1 = new Parent (); Child.prototype = parent1l; This is more obvious. The result of this assignment is that the child is an object that is instantiated by the parent, so child.__proto__ is Parent.prototype. Kid for cihld instantiated object, so: Kid.__proto__ is the Parent to build a prototype chain kid--->child--->parent (child.prototype)---> Parent.prototype thus forms inheritance.

The default mode does not inherit the properties of the ancestor constructor itself, but it can be used only by looking up through the prototype chain. If the successor sets this property for itself, the other identically named attributes on the prototype chain are masked.

Take a look at the output of the above code to see that 14, 15 lines prove that inherited attributes do not create a new property on their own, but only through the prototype up to find the way to get this property, because so 16~19 line of output can be seen, Kid's change to the Name property affects the Name property in the parent constructor.

2. Borrowing Constructors

1        /**2 * [borrowing constructors]3          */4         functionarticle (tags) {5              This. tags = tags | | [' JS ', ' CSS '];6         }7Article.prototype.say =function() {8             return  This. Tags9         }Ten         varArticle =Newarticle (); One         functionStaticpage (tags) { AArticle.apply ( This, arguments); -         } -         varpage =Newstaticpage (); theConsole.log (Page.hasownproperty (' tags '));//true -Console.log (Article.hasownproperty (' tags '));//true -Console.log (Page.tags);//[' JS ', ' CSS '] -Page.tags = [' html ', ' node ']; +Console.log (Page.tags);//[' HTML ', ' node '] -Console.log (Article.tags);//[' JS ', ' CSS '] +         //Console.log (Page.say ());//error undefined is not a function AConsole.log (Article.say ());//[' JS ', ' CSS ']

The above code implementation inherits the 12th line of Article.apply (This,arguments), by calling the article constructor by using the Apply method to change this point ( About This:javascript I would like to talk about this).

It can be seen from the obvious that article and Staticpage are not connected, that is, using the method of borrowing constructors, because the article constructor is used directly to modify the call location, so the attributes inside the article are inherited, and the properties are created independently. However, because Staticpage.prototype is not used, Staticpage automatically creates an empty prototype object. So staticpage did not inherit the method on the article prototype chain.

There's a lot of output in the example code above, so let's look at the reasons for outputting those answers and prove it.

The first 15, 16 lines to determine whether tags are article and page (note that this is the two instantiated objects) of the self-property, the return value is true, it can be explained that Staticpage does inherit the property added to this in article .

17, 18, 19, 20 lines, in the page does not have a special assignment for tags can output the value of the parent structure tags ("js", ' CSS ') when assigned to [' HTML ', ' node '] After the page's tags value changes but the value of article does not change (20 rows), it is obvious that staticpage inheritance article is independent of the creation of its internal properties (because it is the way to modify the call location, so the new properties will be created without association).

21, 22 lines call the Say method. The error proves that the page has not been able to inherit the method on Article.prototype .

3. Borrowing and setting up prototypes (combined inheritance)

1        /**2 * Borrowing and setting up prototypes3          */4         functionBird (name) {5              This. Name = Name | | ' Adam ';6         }7Bird.prototype.say =function() {8             return  This. Name;9         };Ten         functioncatwings (name) { OneBird.apply ( This, arguments); A         } -Catwings.prototype =NewBird (); -         varBird =NewCatwings ("Patrick"); theConsole.log (Bird.name);//Patrick -Console.log (Bird.say ());//Patrick -         DeleteBird.name; -Console.log (Bird.say ());//Adam

The way to borrow and set up a prototype is the most commonly used inheritance pattern, which is combined with the previous two modes by borrowing the constructor and then setting the prototype of the child constructor to point to a new instance created by the constructor.

Catwings first creates a new example using the borrowed constructor bird so that bird can create the name property independently without associating it with the name of the parent constructor. The Catwings.prototype is then assigned to the instantiated object of the bird, which in turn connects the two constructors to a method that the bird object can access on the parent constructor's prototype chain.

4. Sharing prototypes

1         /**2 * Shared Prototypes3          */4         functionA (name) {5              This. Name = Name | | ' Adam ';6         }7A.prototype.say =function(){8             return  This. Name;9         };Ten         functionB () {} OneB.prototype =A.prototype; A         varb =NewB (); - Console.log (b.name); -B.name = ' Lili '; theConsole.log (B.say ());

The above code implementation inherits the 11th line of b.prototype = A.prototype; This code changes the prototype of B to a prototype.

This method is simple, there is not much to explain, but its drawbacks are also very large: it does not inherit the property inside the parent construct, but also can only use the property method on the parent construct prototype, and the child object changes the property or method on the prototype chain and affects the parent element ~

5. Temporary constructors

1         /**2 * Temporary Constructors3          */4         functionC (name) {5              This. Name = Name | | ' Adam ';6         }7C.prototype.say =function() {8             return  This. Name;9         };Ten         functionD () {} One         varCfunction() {}; AE.prototype =C.prototype; -D.prototype =NewE ();

The temporary constructor means to implement inheritance through a temporary constructor, as in line 11 and 12 of the code above.

This figure may not be so easy to understand, but we're focusing on the d.prototype ellipse, and you'll see that it also says new E () Yes, he's an example of an e constructor, and e doesn't have any practical use throughout the inheritance process. His role is only to make a connection to the parent and child constructs, so it is called a temporary constructor. What are the advantages of this? First of all, he can solve the biggest drawback of sharing prototypes is that they can change the same prototype at the same time and affect others, but in this approach, although E and C are shared prototypes, D uses a prototype inherited by default and does not have permission to make changes to C.prototype.

6. Prototype inheritance

Prototype inheritance is very different from the above-mentioned inheritance modes, the above inheritance mode is the inheritance mode of simulation class, but there is no class in prototype inheritance, so it is a kind of class-free inheritance pattern.

1        /**2 * [prototype inheritance]3 * @type {Object}4          */5         functionObject (proto) {6             functionF () {}7F.prototype =Proto;8             return NewF ();9         }Ten  One         varperson = { AName: ' Nana ', -Friends: [' Xiaoli ', ' xiaoming '] -         }; the  -         varAnotherperson =object (person); -AnotherPerson.friends.push (' Xiaohong '); -         varYetanotherperson =object (person); +AnotherPerson.friends.push (' Xiaogang '); -Console.log (person.friends);//["Xiaoli", "Xiaoming", "Xiaohong", "Xiaogang"]
Console.log (anotherperson.__proto__)//object {name: "Nana", Friends:array[4]}

You can see the above 5~9 Line object function through the object function we implement the prototype inheritance. In the entire code, though, Anotherperson and Yetanotherperson inherit from the person object, but there is no constructor.

As can be seen, because the prototype of the constructor is an object, now set an object that needs to be inherited as a prototype of the constructor F, and use this constructor to instantiate an object Anotherperson, so that This object Anotherperson can find the person by the prototype chain and use the attributes or methods above.

In ECMAScript5, this pattern has been implemented by means of object.create (), which means that there is no need to launch a function similar to object (), which is embedded in the JavaScript language.

Since there are a lot of things that I do not understand about the principles of the implementation of JavaScript in my learning process, I have been unable to remember and use this knowledge correctly, so I wrote this blog after I felt that I had some understanding of the inheritance, and the content of the blog was my personal understanding. If there is an explanation is not in place or understand the deviation of the place also ask the great God to tell, the little woman here thanked ~

Graphical JavaScript inheritance

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.