Introduction to the Object-oriented Inheritance-JavaScript Technique in javascript

Source: Internet
Author: User
Tags define abstract
This article mainly introduces the inheritance of JavaScript based on object-oriented. For more information, see I. Face Object Inheritance Mechanism
This example uses UML to explain the inheritance mechanism.
The simplest way to explain the Inheritance Mechanism is to use a classic example of geometric shape. In fact, there are only two kinds of geometric shapes: an elliptical shape (circular shape) and a Polygon Shape (having a certain number of edges ). A circle is a type of elliptic with only one focus. Triangles, rectangles, and Pentagons are polygon with different numbers of edges. A square is a type of rectangle with equal lengths of all edges. This constitutes a perfect inheritance relationship, which effectively explains the Object-oriented Inheritance Mechanism.
In this example, the shape is the base class of the elliptical and polygon (we can also call it the parent class, And all classes are inherited from it ). An elliptic has a genus (foci), indicating the number of focal points that an elliptic has. The circle inherits the elliptical shape, so the circular shape is a subclass of the elliptical shape, and the elliptical shape is a superclass of the circular shape. Likewise, triangles, rectangles, and Pentagons are subclasses of polygon, and polygon are their superclasses. Finally, the square inherits the rectangle.
It is best to use diagrams to explain this inheritance relationship, which is the application of UML (Unified Modeling Language. One of the main purposes of UML is to visually represent complex object relationships such as inheritance. The following figure shows a UML diagram that explains the relationship between a shape and its subclass:

In UML, each box represents a class, which is described by the class name. A triangle, rectangle, and a line segment at the top of a Pentagon point to a shape, indicating that these classes are inherited from the shape. Similarly, the arrows pointing from the square to the rectangle show the inheritance relationship between them.
II. Implementation of ECMAScript Inheritance Mechanism
To use ECMAScript to implement the Inheritance Mechanism, you can start with the base class to be inherited. All classes defined by developers can be used as base classes. For security reasons, the local class and host class cannot be used as the base class. This prevents public access to compiled browser-level code because the code can be used for malicious attacks.
After selecting the base class, you can create its subclass. Whether to use the base class is entirely up to you. Sometimes, you may want to create a base class that cannot be used directly. It is only used to provide a common function for the subclass. In this case, the base class is treated as an abstract class. Although ECMAScript does not strictly define abstract classes as other languages do, it sometimes creates classes that are not allowed to be used. This class is generally called an abstract class.
The created subclass inherits all attributes and methods of the superclass, including constructor and method implementation. Remember that all attributes and methods are public, so sub-classes can directly access these methods. Subclass can also add new attributes and methods that are not present in the superclass, or overwrite the attributes and methods of the superclass. Because Javascript is not an orthodox object-oriented language, some terms also need to be changed.
Iii. Method of ECMAScript inheritance
In ECMAScript, the inherited class (base class) is called a super type, and the subclass (or derived class) is called a child type. Like other functions, ECMAScript implements inheritance in more than one way. This is because the Inheritance Mechanism in JavaScript is not clearly defined, but achieved through imitation. This means that all inheritance details are not completely handled by the interpreter. As a developer, you have the right to decide the most suitable inheritance method. The following describes several inheritance methods.
(1) prototype chain
Inheritance is originally used for prototype chain in ECMAScript. The previous blog article introduced how to create an object prototype. Prototype chain extends this method and implements the Inheritance Mechanism in an interesting way. A prototype object is a template. All objects to be instantiated are based on this template. All in all, any attributes and methods of the prototype object are passed to all instances of that class. Prototype chain uses this function to implement the inheritance mechanism. Let's look at an example:

Function A () {// The parameter this. color = "red"; this. showColor = function () {return this. color ;};}; function B () {// subtype B this. name = "John"; this. showName = function () {return this. name ;};}; B. prototype = new A (); // sub-type B inherits super type A. Through prototype, the chain var a = new A (); var B = new B (); document. write (. showColor (); // output: blue document. write (B. showColor (); // output: red document. write (B. showName (); // output: John

In the prototype chain, the instanceof operator is also unique. For all instances of B, if instanceof is A and B, true is returned. ECMAScript is an extremely useful tool in the weak type world, but it cannot be used when an object is impersonated. For example:

Var B = new B (); document. write (B instanceof A); // output: true document. write (B instanceof B); // output: true

Inheritance is implemented using the prototype chain, but this method cannot be shared or sub-type is passed to the super-type parameter. We can solve these two problems by using the constructor method (that is, image impersonating.
(2) object impersonating
The constructor uses the this keyword to assign values to all attributes and methods (that is, the constructor method of object Declaration ). Because A constructor is just A function, you can make A constructor A method of B and then call it. B receives the attributes and methods defined in the constructor of. For example, you can use the following method to rewrite the above example to create objects A and B:
Call () method

Function A (Color) {// create super type A this. color = Color; this. showColor = function () {return this. color ;};}; function B (Color, Name) {// create A subtype B. call (this, Color); // impersonate an object and pass the parameter this to the super-type. name = Name; // the newly added attribute this. showName =}; var a = new A ("blue"); var B = new B ("red", "John"); document. write (. showColor (); // output: blue document. write (B. showColor (); // output: red document. write (B. showName (); // output: John

Apply () method
The only difference from the preceding call () method is the code in child Type B:
A. call (this, arguments); // impersonate an object and PASS Parameters of the super type
Of course, parameter objects can be passed only when the Parameter order in the super type is exactly the same as that in the sub-type. If not, you must create a separate array and place the parameters in the correct order.
Although the object impersonating method solves the problem of sharing and passing parameters, there is no prototype, and reuse is even more impossible. Therefore, we combine the above two methods, that is, the prototype chain method and the object impersonate method realize JS inheritance.
(3) hybrid mode
This inheritance method uses constructors to define classes, rather than any prototype. The main problem with object impersonation is that the constructor method must be used, which is not the best choice. However, if the prototype chain is used, the constructor with parameters cannot be used. How do Developers choose? The answer is simple. Both are used. Because this hybrid method uses the prototype chain, the instanceof operator can still run correctly.
In the previous article, the best way to create an object is to use constructors to define attributes and prototype to define attributes. This method also applies to the Inheritance Mechanism. It uses an object to impersonate the attributes of the inherited constructor and uses the prototype object method of the prototype chain. Use these two methods to rewrite the previous example. The Code is as follows:

Function A (Color) {this. color = Color;};. prototype. showColor = function () {return this. color ;}; function B (Color, Name) {. call (this, Color); // The object impersonates this. name = Name ;}; B. prototype = new A (); // use the prototype chain to inherit B. prototype. showName = function () {return this. name ;}; var a = new A ("blue"); var B = new B ("red", "John"); document. write (. showColor (); // output: blue document. write (B. showColor (); // output: red document. write (B. showName (); // output: John

The Inheritance Method is related to the object creation method. We recommend that you use a hybrid inheritance method that combines the prototype chain with the object impersonating. This hybrid approach can avoid unnecessary problems.
When reading this article, you must check the previous object creation method:Detailed description of JavaScript Object creation based on object-oriented (1)AndDetailed description of JavaScript Object creation based on object-oriented (2).

The above is all the content of this article, hoping to help you learn.

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.