Class inheritance implementation mechanism in prototype framework
CopyCode The Code is as follows: // Add a static method for the object class: Extend
Object. Extend = function (destination, source ){
For (property in source ){
Destination [property] = source [property];
}
Return destination;
}
// Use the object class to add the extend method for each object
Object. Prototype. Extend = function (object ){
Return object. Extend. Apply (this, [This, object]);
}
The object. Extend method is easy to understand. It is a static method of the object class. It is used to assign all the properties of source in the parameter to the destination object and return the reference of destination. The following describes the implementation of object. Prototype. Extend. Because object is the base class of all objects, an extend method is added for all objects. The statement in the function body is as follows:
Object. Extend. Apply (this, [This, object]);
This statement runs the static method of the object class as the method of the object. The first parameter This is pointing to the object instance itself, and the second parameter is an array containing two elements: object itself and the passed object parameter object. The function assigns all attributes and methods of the parameter object to the object that calls the method and returns its reference. With this method, we can see the implementation of class inheritance below: Copy code The Code is as follows: <script language = "JavaScript" type = "text/JavaScript">
<! --
// Define the extend Method
Object. Extend = function (destination, source ){
For (property in source ){
Destination [property] = source [property];
}
Return destination;
}
Object. Prototype. Extend = function (object ){
Return object. Extend. Apply (this, [This, object]);
}
// Define class1
Function class1 (){
// Constructor
}
// Define the class class1 Member
Class1.prototype = {
Method: function (){
Alert ("class1 ");
},
Method2: function (){
Alert ("method2 ");
}
}
// Define class2
Function class2 (){
// Constructor
}
// Let class2 inherit from class1 and define new members
Class2.prototype = (New class1 (). Extend ({
Method: function (){
Alert ("class2 ");
}
});
// Create two instances
VaR obj1 = new class1 ();
VaR obj2 = new class2 ();
// Test the obj1 and obj2 Methods
Obj1.method ();
Obj2.method ();
Obj1.method2 ();
Obj2.method2 ();
// -->
</SCRIPT>
The running result shows that the inheritance is correctly implemented, and the additional members of the derived class can also be defined in the form of a list.