Implementation of JavaScript Inheritance Mechanism

Source: Internet
Author: User
Tags define abstract

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 attributes and methods in the superclass.

4.2.1 Inheritance Method

Like other functions, ecmascript has more than one method to implement inheritance. This is because the Inheritance Mechanism in Javascript is not clearly defined, but achieved through imitation. This means that all inheritance details are not explainedProgramProcessing. As a developer, you have the right to decide the most suitable inheritance method.

1. Object impersonating

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

The principle is as follows: the constructor uses the this keyword to assign values to all attributes and methods (that is, the constructor method of class Declaration ). Because the constructor is just a function, you can make the constructor of classa A classb method and then call it. Classb receives the attributes and methods defined in the classa constructor. For example, use the following method to define classa and classb:

Remember? This keyword references the object Currently created by the constructor. However, in this method, this points to the object to which it belongs. This principle is to use classa as a general function to establish an inheritance mechanism, rather than as a constructor. The following uses the constructor classb to implement the Inheritance Mechanism:

In this sectionCode(Remember, 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 deleted. Otherwise, the attributes and methods of the superclass may be overwritten:

To verify that the preceding code is valid, run the following example:

Interestingly, object impersonation supports multi-inheritance. That is to say, a class can inherit multiple superclasses. The multi-Inheritance Mechanism represented by UML is shown in Figure 4-2.

Figure 4-2

For example, if there are two classes classx and classy and classz want to inherit these two classes, you can use the following code:

There is a drawback here. If classx and classy have attributes or methods of the same name, classy has a high priority because it inherits the final class. In addition to this small problem, it is easy to use object impersonate multiple inheritance mechanisms.

Due to the popularity of this inheritance method, the third edition of ecmascript adds two new methods to the function object, namely call () and apply ().

2.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:

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 "red ". 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 prefix and suffix parameters in the saycolor () function. The final message "the color is red, 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:

Here, we want the keyword "this" in classa to be equal to the newly created classb object, so "this" is the first parameter. The second parameter scolor is a unique parameter for both classes.

3.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:

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, indicating that the value of this keyword in saycolor () should be given to OBJ. The second parameter is an array composed of two strings. It matches the prefix and suffix parameters of saycolor. The generated message is still "the color is red, a very nice color indeed" and 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:

Similarly, the first parameter is still this. The second parameter is an array with only one color value. You can pass the entire arguments object of classb to the apply () method as the second parameter:

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.

4. prototype chain

Inheritance is originally used for prototype chain in ecmascript. The previous chapter describes how to define the prototype of a class. Prototype chain extends this method and implements the Inheritance Mechanism in an interesting way.

As I learned in the previous chapter, prototype objects are templates. 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:

The magic of the prototype chain is the highlighted code lines. Set the prototype attribute of classb to the instance of classa. This makes sense because you want to assign all attributes and methods of classa to the prototype attribute of classb one by one. Is there a better way to grant the prototype attribute to the classa instance?

Note: CallClassaThe constructor does not pass parameters to the constructor. This is a standard practice in the prototype chain. Make sure that the constructor does not have any parameters.

Similar to object impersonating, all attributes and methods of the subclass must appear after the prototype attribute is assigned a value, because all methods assigned before it are deleted. Why? Because the prototype attribute is replaced with a new object, the original object added with the new method will be destroyed. Therefore, the code for adding the name attribute and sayname () method to the classb class is as follows:

You can test this code by running the following example:

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. For example:

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.

5. hybrid mode

This inheritance method uses constructors to define classes without any prototype. The main problem with object impersonating is that you must use the constructor method (as learned in the previous chapter), which is not the best choice. However, if the prototype chain is used, the constructor with parameters cannot be used. How Should Developers choose? The answer is simple. Both are used.

In the previous chapter, the best way to create a class is to define attributes using constructors and define methods using prototypes. 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:

In this example, the inheritance mechanism is implemented by two lines of highlighted code. In the Code highlighted in the first line, in the classb constructor, The scolor attribute of the classa class is inherited by impersonating an object. In the highlighted code in the second line, use the prototype chain to inherit the classa class method. Because this hybrid method uses the prototype chain, the instanceof operator can still run correctly.

The following example tests the Code:

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.