Imitation implementation of inheritance mechanism in JavaScript

Source: Internet
Author: User
Tags define abstract

First, we use a classic example to briefly explain the inheritance mechanism in ECMAScript.

In geometry, there are essentially only two geometric shapes, the oval (which is circular) and the polygon (with a certain number of edges). A circle is a type of ellipse that has only one focus. Triangles, rectangles, and Pentagon are all polygons, with different numbers of edges. A square is one of the rectangles, and all sides are equal in length. This constitutes a perfect inheritance relationship.

In this example, the shape is the base class (base class) of the Ellipse (Ellipse) and Polygon (Polygon) (all classes inherit from it). The ellipse has an attribute foci that indicates the number of focal points the ellipse has. The Circle (circle) inherits the ellipse, so the circle is the subclass of the ellipse (subclass), and the ellipse is a circle-like superclass (superclass). Similarly, triangles (Triangle), rectangles (Rectangle), and Pentagon (Pentagon) are sub-classes of polygons, which are their superclass. Finally, the square inherits the rectangle. Nenjiang County Ocean Bureau

To implement the inheritance mechanism with ECMAScript, you can start with the base class that you want to inherit from. All developer-defined classes are available as base classes. For security reasons, local classes and host classes cannot be used as base classes, which prevents public access to compiled browser-level code because the code can be used for malicious attacks. Once you have selected a base class, you can create its subclasses. It is up to you to use the base class. Sometimes, you might want to create a base class that you can't use directly, it's just used to provide generic functions to subclasses. In this case, the base class is treated as an abstract class. Although ECMAScript does not define abstract classes as strictly as in other languages, it does sometimes create classes that are not allowed to be used. In general, we call this class an abstract class. The subclass you create inherits all the properties and methods of the superclass, including the implementation of constructors and methods. Remember that all properties and methods are common, so subclasses can access these methods directly. Subclasses can also add new properties and methods that are not in the superclass, or override the properties and methods of the superclass.

Although we use the term "class" above, there is actually no definition of the class in ECMAScript. We just want to be able to describe the inheritance mechanism in an image. ECMAScript implements inheritance in more than one way. This is because the inheritance mechanism in JavaScript is not explicitly defined, but is implemented by imitation. This means that all inheritance details are not handled entirely by the interpreter. As a developer, you have the right to decide on the most appropriate way to inherit.

Object Impersonation

When the original ECMAScript was conceived, there was no intention to design the object to impersonate (object masquerading). It is when developers begin to understand how functions work, especially how to use the This keyword in a function environment to develop.

function ClassA (scolor) {this.color = Scolor;this.saycolor = function () {alert (this.color);};} function ClassB (Scolor, sName) {this.newmethod = ClassA;   Add a new method Newmethod for CLASSB, which references Classathis.newmethod (scolor);    Delete This.newmethod; To avoid affecting the properties and methods of ClassA, the method is destroyed. Because the function ClassA just refers to the value this.name = Sname;this.sayname = function ()     {alert (this.name);};    } var obja = new ClassA ("Blue"), var objb = new ClassB ("Red", "John"); Obja.saycolor (); Eject "Blue" objb.saycolor (); Pop up "Red" objb.sayname (); Pop Up "John"

The constructor uses the This keyword to assign values to all properties and methods (that is, the constructor method that takes the class declaration). Because the constructor is just a function, you can make the ClassA constructor a ClassB method and then call it. ClassB will receive the properties and methods defined in the ClassA constructor. In this method, ClassA is used as a regular function to establish the inheritance mechanism, rather than as a constructor function. Add the Newmethod method to ClassB, which references ClassA (the function name is just a pointer to it). The method is then called, and passed to it is the parameter scolor of the ClassB constructor. The last line of code removes a reference to ClassA so that it can no longer be called. All new properties and new methods must be defined after the line of code in which the new method is uploaded. Otherwise, the related properties and methods that are extremely tiring may be overwritten.

Object impersonation can implement multiple inheritance. For example, if there are two classes CLASSX and Classy,classz want to inherit these two classes, you can use the following code:

function Classz () {    this.newmethod = CLASSX;    This.newmethod ();    Delete This.newmethod;    This.newmethod = classy;    This.newmethod ();    Delete This.newmethod;}

Due to the popularity of this inheritance method, the third edition of ECMAScript added two methods to the Function object, call () and apply ().

Call () method

The call () method is the most similar method to the Classic object impersonation method. Its first parameter is used as the object of this. Other parameters are passed directly to the function itself. For example:

function Saycolor (sprefix,ssuffix) {alert (Sprefix + This.color + ssuffix);}; var obj = new Object (); obj.color = "Blue"; Saycolor.call (obj, "The color is", "a very nice color indeed.");

In addition, in the prototype chain, the instanceof operator operates in a unique way. For all instances of ClassB, instanceof returns true for both ClassA and ClassB.

In this example, the function Saycolor () is defined outside the object, and even if it does not belong to any object, it can also refer to the keyword this. The color property of the object obj is equal to blue. When the call () method is called, the first parameter is obj, stating that the This keyword value in the Saycolor () function should be given to obj. The second and third arguments are strings. They match the parameters Sprefix and Ssuffix in the Saycolor () function, and the last generated message "The color is blue, a very nice color indeed." will be displayed.

To use this method with an object that inherits from the mechanism, simply replace the assignment, call, and delete code for the first three rows:

function ClassB (Scolor, sName) {    //this.newmethod = ClassA;    This.newmethod (color);    Delete This.newmethod;    Classa.call (this, scolor);    THIS.name = SName;    This.sayname = function () {        alert (this.name);    };

Here, we need to make the ClassA keyword this equal to the newly created ClassB object, so this is the first parameter. The second parameter, Scolor, is the only parameter for two classes.

Apply () method

The Apply () method has two parameters, the object used as the this and an array of arguments to pass to the function. For example:

function Saycolor (sprefix,ssuffix) {    alert (sprefix + This.color + ssuffix);}; var obj = new Object (); obj.color = "Blue"; saycolor.apply (obj, New Array ("The Color is", "a very nice color indeed."));

This example is the same as the previous example, except that the Apply () method is now called. When the Apply () method is called, the first parameter is still obj, stating that the This keyword value in the Saycolor () function should be assigned to obj. The second parameter is an array of two strings, matching the parameters Sprefix and Ssuffix in the Saycolor () function, and the last generated message is still "The color is blue, a very nice color indeed.", will be displayed 。

The method is also used to replace the first three rows of the assignment, call, and delete code for the new method:

function ClassB (Scolor, sName) {    //this.newmethod = Classa;//this.newmethod (color);//delete This.newmethod;    Classa.apply (This, new Array (Scolor));    THIS.name = SName;    This.sayname = function () {        alert (this.name);    };}

Similarly, the first argument is still this, and the second argument is an array with only one value of color. You can pass the entire arguments object of ClassB as the second argument to the Apply () method:

function ClassB (Scolor, sName) {    //this.newmethod = Classa;//this.newmethod (color);//delete This.newmethod;    Classa.apply (this, arguments);    THIS.name = SName;    This.sayname = function () {        alert (this.name);    };}

Of course, a parameter object can be passed only if the order of the parameters in the superclass is exactly the same as the order of the parameters in the subclass. If not, you must create a separate array to place the parameters in the correct order. In addition, you can use the call () method.

Prototype chain

This form of inheritance was originally used for prototype chains in ECMAScript. The prototype object is a template, and the object to instantiate is based on this template. In summary, any properties and methods of the prototype object are passed to all instances of that class. The prototype chain uses this function to implement the inheritance mechanism.

If you re-define the classes in the previous example in a prototype way, they will become the following form:

function ClassA (scolor) {this.color = Scolor;} ClassA.prototype.sayColor = function () {alert (this.color);}; function ClassB (Scolor, SName) {Classa.call (this, scolor); this.name = SName;} Classb.prototype = Classa.prototype; Classb.prototype = new ClassA (); Call ClassA's constructor without passing arguments to it. This is standard practice in the prototype chain. To ensure that the constructor has no parameters ClassB.prototype.sayName = function () {alert (this.name);}; var obja = new ClassA ("Blue"), var objb = new ClassB ("Red", "John"); Obja.saycolor (); 24objb.saycolor (); 25objb.sayname ();

This is an extremely useful tool in ECMAScript's weakly-typed world, but it cannot be used when impersonating an object. The drawback of the prototype chain is that multiple inheritance is not supported. Remember that the prototype chain overrides the prototype property of the class with another type of object.

Blending mode

This inheritance uses constructors to define classes, not using any prototypes. The main problem with object impersonation is that the constructor must be used, which is not the best choice. However, if you use a prototype chain, you cannot use a constructor with parameters. How do developers choose? The answer is simple, both are used. is to define a property with a constructor and define the method with a prototype. This approach also applies to the inheritance mechanism, using the object to impersonate the inheritance constructor property, using the prototype chain to inherit the method of the prototype object. Rewrite the previous example in either of these ways, with the following code:

function ClassA (scolor) {this.color = Scolor;} ClassA.prototype.sayColor = function () {alert (this.color);}; function ClassB (Scolor, SName) {Classa.call (this, scolor);     In the ClassB constructor, the Scolor property of the ClassA class is inherited with the object this.name = SName;} Classb.prototype = new ClassA ();   The method of inheriting the ClassA class with the prototype chain ClassB.prototype.sayName = function () {alert (this.name);};

Imitation implementation of inheritance mechanism in 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.