1024programmer Java Implementation of Javascript inheritance mechanism_javascript skills

Implementation of Javascript inheritance mechanism_javascript skills

After selecting a base class, you can create its subclasses. It’s entirely up to you whether to use a base class or not. Sometimes, you may want to create a base class that cannot be used directly, but is only used to provide common functions to subclasses. In this case, the base class is considered an abstract class.


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


The created subclass will inherit all properties and methods of the superclass, including the implementation of constructors and methods. Remember, all properties and methods are public, so subclasses can access these methods directly. Subclasses can also add new properties and methods that are not found in the superclass, or they can override properties and methods in the superclass.


4.2.1 Inheritance methods


As with other features, there is more than one way to implement inheritance in ECMAScript. This is because the inheritance mechanism in Javascript is not explicitly specified, but is implemented through imitation. This means that all inheritance details are not handled by the interpreter. As the developer, you have the right to decide the inheritance method that works best for you.


1. Object impersonation


When the original ECMAScript was conceived, object masquerading was not intended at all. It was developed after developers began to understand how functions work, especially how to use the this keyword in a function context.


The principle is as follows: the constructor uses the this keyword to assign values ​​to all properties and methods (that is, using the constructor method of class declaration). Because the constructor is just a function, you can make the constructor of ClassA a method of ClassB and then call it. ClassB will receive the properties and methods defined in the constructor of ClassA. For example, define ClassA and ClassB in the following way:



Remember? The keyword this refers to the object currently created by the constructor. But in this method, this points to the object it belongs to. The principle is to use ClassA as a regular function to establish an inheritance mechanism, rather than as a constructor. The inheritance mechanism can be implemented using the constructor ClassB as follows:



In this code, the method newMethod is assigned to ClassA (remember , the function name is just a pointer to it). The method is then called, passing it the parameter sColor of the ClassB constructor. The last line of code removes the reference to ClassA so that it can no longer be called in the future.


All new properties and new methods must be defined after deleting the new method’s line of code. Otherwise, the relevant properties and methods of the superclass may be overridden:



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



Interestingly, object impersonation can support multiple inheritance. That is, a class can inherit from multiple superclasses. The multiple 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 wants to inherit these two classes, you can use the following code:




There is a drawback here. If ClassX and ClassY have properties or methods with the same name, ClassY has high priority because it is the last class that is inherited. Apart from this small problem, it is easy to implement multiple inheritance mechanisms using object impersonation.


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


2. call()method


The call() method is the method most similar to the classic object impersonation method. Its first parameter serves as the object of this. All other parameters are passed directly 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 property of object obj is equal to “red”. When calling the call() method, the first parameter is obj, which means that the value of this keyword in the sayColor() function should be given as obj. The second and third parameters are strings. They match the parameters prefix and suffix in the sayColor() function, and the final generated message “The color is red, a very nice color indeed” will be displayed.


To use this method with the inheritance mechanism’s object impersonation methods, simply change the first three lines of assignment, �Just replace it with and delete the code:



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 the only parameter for both classes.


3. apply()method


The

apply() method takes 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, except now the apply() method is called. When calling the apply() method, the first parameter is still obj, which means that the value of this keyword in sayColor() should be given as obj. The second parameter is an array composed of two strings, matching the parameters prefix and suffix of sayColor(). The resulting message is still “The color is red, a very nice color indeed” and will be displayed.


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




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



Of course, only the order of parameters in the super class is the same as the parameters in the subclass Parameter objects can be passed only when the order is exactly the same. If not, you’ll have to create a separate array with the parameters in the correct order. In addition, the call() method can also be used.


4. Prototype chain


This form of inheritance was originally used for prototype chains in ECMAScript. The previous chapter introduced the prototype way of defining classes. Prototype chains extend this approach to implement the inheritance mechanism in an interesting way.


As learned in the previous chapter, the prototype object is a template, and the objects to be instantiated are 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 utilizes this functionality to implement the inheritance mechanism.


If you redefine the classes in the previous example using prototypes, they will become the following:



The magic of the prototype chain lies in the highlighted lines of code. Here, set the prototype attribute of ClassB to an instance of ClassA. This makes sense because you want all the properties and methods of ClassA, but don’t want to assign them to ClassB’s prototype property one by one. Is there a better way than assigning an instance of ClassA to the prototype attribute?

Note that when calling the constructor of ClassA, no parameters are passed to it. This is standard practice in prototype chains. Make sure the constructor doesn’t have any parameters.


Similar to object impersonation, all attributes and methods of the subclass must appear after the prototype attribute is assigned, because all methods assigned before it will be deleted. Why? Because the prototype attribute is replaced with the new object, the original object with the new method added will be destroyed. Therefore, the code to add the name attribute and sayName() method to the ClassB class is as follows:




This code can be tested by running the following example:



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



This is an extremely useful tool in the weakly typed world of ECMAScript, but it cannot be used when using object impersonation.


The disadvantage of the prototype chain is that it does not support multiple inheritance. Remember, the prototype chain overrides the prototype property of a class with an object of another type.


5. Mixed method


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


In the previous chapter, you learned that the best way to create a class is to define properties using constructors and methods using prototypes. This method also applies to the inheritance mechanism, using objects to pretend to inherit the properties of the constructor, and using the prototype chain to inherit the methods of the prototype object. Rewrite the previous example in these two ways, the code is as follows:




In this example, the inheritance mechanism is implemented by the two highlighted lines of code. In the first highlighted line of code, in the ClassB constructor, an object is used to pretend to inherit the sColor property of the ClassA class. In the second highlighted line of code, methods of the ClassA class are inherited using the prototype chain. Since this hybrid approach uses the prototype chain, the instanceof operator still works correctly.


The following example tests this code:



Rewrite the previous example in two ways, the code is as follows:




In this example, the inheritance mechanism is implemented by the two highlighted lines of code. In the first highlighted line of code, in the ClassB constructor, an object is used to pretend to inherit the sColor property of the ClassA class. In the second highlighted line of code, methods of the ClassA class are inherited using the prototype chain. Since this hybrid approach uses the prototype chain, the instanceof operator still works correctly.


The following example tests this code:


This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/722318

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索