Implementation _javascript Techniques of Javascript inheritance mechanism

Source: Internet
Author: User
Tags define abstract

Once you have selected a base class, you can create its subclasses. It is entirely up to you to decide whether to use the base class. Sometimes, you might want to create a base class that you can't use directly, it's just for providing a generic function to a subclass. In this case, the base class is treated as an abstract class.

Although ECMAScript does not define abstract classes as rigorously as other languages, it does sometimes create classes that are not allowed to be used. Typically, we call this class an abstract class.

The subclass you create inherits all of the properties and methods of the superclass, including the constructor and the implementation of the method. Remember that all properties and methods are public, so subclasses can access these methods directly. Subclasses can also add new properties and methods that are not in the superclass, or override properties and methods in the superclass.

4.2.1 Way of inheriting

As with other functions, there are more than one way to implement inheritance in ECMAScript. This is because the inheritance mechanism in JavaScript is not explicitly defined, but is done by imitation. This means that all the details of the inheritance are not handled by the interpreter. As a developer, you have the right to decide the most appropriate way to inherit.

1. Object posing as

When the original ECMAScript was conceived, there was no intention of designing objects to impersonate (object masquerading). It is developed when developers begin to understand how functions work, especially when using the This keyword in a functional environment.

The principle is as follows: The constructor uses the This keyword to assign values to all properties and methods (that is, the constructor method declared by the class). 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. For example, define ClassA and CLASSB in the following ways:

Do you remember? Keyword this refers to the object that the constructor is currently creating. In this method, however, this points to the object to which it belongs. The principle is to use ClassA as a regular function to establish an inheritance mechanism, not as a constructor. You can implement the inheritance mechanism using the constructor ClassB as follows:

In this code, the ClassA is given a method Newmethod (remember, the function name is just the 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 deletes a reference to ClassA so that it cannot be invoked later.

All new properties and new methods must be defined after the line of code for the new method has been deleted. Otherwise, the related properties and methods of the superclass may be overwritten:

To prove that the preceding code is valid, you can run the following example:

Interestingly, object impersonation can support multiple inheritance. In other words, a class can inherit multiple superclass classes. The multiple inheritance mechanism represented in UML is shown in Figure 4-2.

Figure 4-2

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

There is a disadvantage that if CLASSX and classy have a property or method with the same name, classy has a high priority because the last class is inherited. In addition to this small problem, it is easy to use object as a mechanism to implement multiple inheritance.

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

2. Call () method

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

In this example, the function Saycolor () is defined outside the object, even if it does not belong to any object, or it can refer to the keyword this. The Color property of object obj equals "red". When calling the call () method, the first argument is obj, which indicates that the this keyword value in the Saycolor () function should be given as obj. The second and third arguments are strings. They match the parameters prefix and suffix in the saycolor () function, and the resulting message "The color is red, a very nice color indeed" will be displayed.

To use this method with the object impersonation method of an inheritance mechanism, you can simply replace the first three rows with the assignment, invocation, and deletion code:

Here, you want the keyword in ClassA to be equal to the newly created CLASSB object, so this is the first argument. The second parameter, Scolor, is the only parameter for two classes.

3. apply () method

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

This example is the same as the previous example, except that the Apply () method is now being invoked. When the Apply () method is invoked, the first argument is still obj, stating that the This keyword value in Saycolor () should be given as obj. The second argument is an array of two strings that match the parameters of Saycolor () prefix and suffix. The generated message remains "The color is red, a very nice color indeed" and will be displayed.

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

Again, the first argument is still this. The second argument is an array of only one value color. You can pass the entire arguments object of CLASSB as the second parameter to the Apply () method:

Of course, parameter objects 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 and place the parameters in the correct order. In addition, you can use the call () method.

4. Prototype chain

This form of inheritance was originally used for the prototype chain in ECMAScript. The previous chapter describes how to define a prototype for a class. The prototype chain extends this way and implements inheritance in an interesting way.

In the previous chapter, the prototype object was a template, and the objects to be instantiated were 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 redefine the classes in the previous example in a prototype way, they will change to the following form:

The magic of the prototype chain is the highlighted lines of code. Here, set the CLASSB prototype property to an instance of ClassA. This is meaningful because you want to classa all the properties and methods, but do not want to assign them individually to CLASSB prototype properties. Is there a better way to give prototype properties to the ClassA instance?

Note that when the ClassA constructor is invoked, no arguments are passed to it. This is standard practice in the prototype chain. Make sure that the constructor does not have any arguments.

As with object impersonation, all of the properties and methods of a subclass must appear after the prototype property is assigned, because all methods of assigning values before it are deleted. Why? Because the prototype property is replaced with a new object, the original object that was added to the new method is destroyed. Therefore, the code for adding the Name property and the Sayname () method for the ClassB class is as follows:

You can test this code by running the following example:

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

This is an extremely useful tool in the weak-type world of ECMAScript, but it cannot be used when the object is impersonating.

The disadvantage 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.

5. Blending mode

This inheritance uses constructors to define classes and does not use any prototypes. The main problem with object impersonation is that you must use a constructor method (as you learned in the previous chapter), which is not the best choice. However, if you use a prototype chain, you cannot use the parameter constructor. How do developers choose to do that? The answer is simple, both are used.

In the previous chapter, you learned that the best way to create a class is to define the attribute in a constructor way and define the method in a prototype way. This approach also applies to inheritance mechanisms, using objects to impersonate inherited constructor properties, and using a prototype chain to inherit prototype objects. Rewrite the previous example in both ways, with the following code:

In this example, the inheritance mechanism is implemented by two lines of highlighted code. In the first line of highlighted code, in the ClassB constructor, an object is used to impersonate an inherited ClassA class's Scolor property. In the second line of highlighted code, the method of inheriting the ClassA class with a prototype chain. The instanceof operator still works correctly because the prototype chain is used in this blending mode.

The following example tests this code:

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.