Ecmascript Inheritance Mechanism implementation

Source: Internet
Author: User
Tags define abstract
ArticleDirectory
    • Inheritance Method
    • Object impersonating can implement multi-Inheritance
Implementation of Inheritance Mechanism

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, which prevents public access to compiled browser-levelCodeBecause 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,But sometimes it does create some 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, all attributes and methods are public.Therefore, 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.

Inheritance Method

Like other functions, 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 explained.ProgramProcessing. As a developer, you have the right to decide the most suitable inheritance method.

The following describes several inheritance methods.

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.

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 classa constructor 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:

 
Function classa (scolor) {This. Color = scolor; this. saycolor = function () {alert (this. Color) ;}}function classb (scolor ){}

 

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:

 
Function classb (scolor) {This. newmethod = classa; this. newmethod (scolor); Delete this. newmethod ;}

 

In this Code, the newmethod (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:

 
Function classb (scolor, sname) {This. newmethod = classa; this. newmethod (scolor); Delete this. newmethod; this. name = sname; this. sayname = function () {alert (this. name );};}

 

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

 
VaR obja = new classa ("blue"); var objb = new classb ("red", "John"); obja. saycolor (); // output "blue" objb. saycolor (); // output "red" objb. sayname (); // output "John"
Object impersonating can implement multi-Inheritance

Interestingly, object impersonation supports multi-inheritance. That is to say, a class can inherit multiple superclasses. Shows the multiple inheritance mechanisms represented by UML:

 

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 ;}

 

There is a drawback here. If two classes classx and classy have attributes or methods with the same name,Classy has a high priority because it inherits from the following 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 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 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 chaining)

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.

The 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 () {} classa. prototype. color = "blue"; classa. prototype. saycolor = function () {alert (this. color) ;}; function classb (){}Classb. Prototype = new classa ();

 

The magic of prototype is the highlighted pink line of code. Set the prototype attribute of classb to the instance of classa. This is interesting because you want all the attributes and methods of classa, but you do not want to classify the prototype attributes of classb one by one. Is there a better way to grant the prototype attribute to the classa instance?

Note: The classa constructor is called and no parameters are passed to it. 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:

 
Function classb () {} classb. prototype = new classa (); classb. prototype. name = ""; classb. prototype. sayname = function () {alert (this. name );};

 

You can test this code by running the following example:

 
VaR obja = new classa (); var objb = new classb (); obja. color = "blue"; objb. color = "red"; objb. name = "John"; obja. saycolor (); objb. saycolor (); objb. sayname ();

 

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:

 
VaR objb = new classb (); alert (objb instanceof classa); // output "true" alert (objb instanceof classb); // output "true"

 

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.

In the previous chapter, we have explained that the best way to create a class is to define attributes using constructors and define attributes 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:

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 = new classa ();Classb. Prototype. sayname = function () {alert (this. Name );};

 

In this example, the inheritance mechanism is implemented by two lines of highlighted pink 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:

 
VaR obja = new classa ("blue"); var objb = new classb ("red", "John"); obja. saycolor (); // output "blue" objb. saycolor (); // output "red" objb. sayname (); // output "John"

 

 

reprinted statement: This article is transferred from http://www.w3school.com.cn/js/pro_js_inheritance_implementing.asp (w3school)

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.