Imitation of Inheritance Mechanism in JavaScript

Source: Internet
Author: User
Tags define abstract

First, we will use a classic example to briefly describe the Inheritance Mechanism in ECMAScript.

There are only two types of geometric shapes, namely, the elliptical shape (circular shape) and the 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. For example:

In this example, Shape is the base class of Ellipse and Polygon (inherited from all classes ). An elliptic has a foci attribute, 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 (subclass) and the elliptical shape is a superclass of the circular shape (superclass ). Likewise, triangles, rectangles, and Pentagons are subclasses of polygon, and polygon are their superclasses. Finally, Square inherits the rectangle.

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.

Although the term "class" is used above, in fact, ECMAScript does not define classes. We only need to be able to visually describe the inheritance mechanism. 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.

Object impersonating

When the original ECMAScript was conceived, there was no intention of designing object masquerading ). It is developed after developers start to understand the function, especially how to use the this keyword in the function environment.

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; // destroy this method to avoid affecting the attributes and methods of ClassA. Because the function ClassA only references the value this. name = sName; this. sayName = function () {alert (this. name) ;};} var objA = new ClassA ("blue"); var objB = new ClassB ("red", "John"); objA. sayColor (); // The "blue" objB is displayed. sayColor (); // the pop-up "red" objB. sayName (); // "John" is displayed"

Constructors use the this keyword to assign values to all attributes and methods (that is, the class declaration constructor method ). Because the constructor is just a function, you can make the ClassA constructor A ClassB method and then call it. ClassB receives the attributes and methods defined in the ClassA constructor. In this method, ClassA is used as a general function to establish an inheritance mechanism, rather than as a constructor. Add the newMethod Method for ClassB. This method references ClassA (the function name is just a pointer to it ). Call this method and pass it the sColor parameter of the ClassB constructor. The last line of code deletes the reference to ClassA, so that it cannot be called later. All new attributes and methods must be defined after the code line of the new method is uploaded. Otherwise, the related properties and methods that are too tired may be overwritten.

Object impersonating can implement multiple inheritance. For example, if there are two classes ClassX and ClassY and 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 adds two methods to the Function object, namely call () and apply ().

Call () method

The call () method is the most similar to the classic object impersonating method. Its first parameter is used as the object of this. Other parameters are directly passed 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, the instanceof operator is also unique in the prototype chain. For all instances of ClassB, if instanceof is ClassA or ClassB, true is returned.

In this example, the function sayColor () is defined outside the object, and the keyword this can be referenced even if it does not belong to any object. The color attribute of object obj is equal to blue. When calling the call () method, the first parameter is obj, which indicates that the value of this keyword in the sayColor () function should be given to obj. The second and third parameters are strings. They match The sPrefix and sSuffix parameters in The sayColor () function. The final message "The color is blue, a very nice color indeed." will be displayed.

To use this method together with the object impersonating method of the Inheritance Mechanism, you only need to replace the values, calls, and deletion codes of 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 keyword this in ClassA equal to the newly created ClassB object, so this is the first parameter. The second parameter sColor is a unique parameter for both classes.

Apply () method

The apply () method has two parameters: the object used as this and the array of parameters to be passed 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, but now the apply () method is called. When the apply () method is called, the first parameter is still obj, which indicates that the value of this keyword in the sayColor () function should be given to obj. The second parameter is an array composed of two strings. It matches The sPrefix and sSuffix parameters in The sayColor () function. The final message is still "The color is blue, a very nice color indeed. ", will be displayed.

This method is also used to replace the code for assigning values to, calling, and deleting new methods in the first three rows:

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 parameter is still this, and the second parameter is an array with only one value of color. You can pass the entire arguments object of ClassB to the apply () method as the second parameter:

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, parameter objects can be passed only when the Parameter order in the superclass is exactly the same as that in the subclass. If not, you must create a separate array and place the parameters in the correct order. You can also use the call () method.

Prototype chain

Inheritance is originally used for prototype chain in ECMAScript. 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.

If you use a prototype to redefine the classes in the previous example, they will become in 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 the ClassA constructor without passing parameters. This is a standard practice in the prototype chain. Make sure that the constructor does not have any parameter 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 the weak type world of ECMAScript, but it cannot be used when an object is impersonated. The disadvantage of prototype chain is that it does not support multiple inheritance. Remember, the prototype attribute of the class will be overwritten by another type of object.

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. Is to use constructors to define attributes, and use 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 ClassA (sColor) {this. color = sColor;} ClassA. prototype. sayColor = function () {alert (this. color) ;}; function ClassB (sColor, sName) {ClassA. call (this, sColor); // In the ClassB constructor, use an object to pretend to inherit the sColor attribute of the ClassA class this. name = sName;} ClassB. prototype = new ClassA (); // use the prototype chain to inherit the ClassB class method. prototype. sayName = function () {alert (this. name );};

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.