Class inheritance is familiar to most developers. As long as they have classes with methods, they can be instantiated as objects.
Below is a simple method to simulate class inheritance.CodeThe list is as follows:
<Script>
// Auxiliary Function Definition
Function. Prototype. Method = Function (Name, func ){
This . Prototype [name] = Func;
Return This ;
}
// Implementation Functions
Function. Method ( ' Inherits ' , Function (Parent ){
// Record the level of the current parent level
VaR Depth = 0 ;
// Methods for inheriting parent objects
VaR PROTO = This . Prototype = New Parent ();
// Privileged functions
This . Method ( ' Uber ' , Function Uber (name ){
VaR Func;
VaR RET;
VaR V = Parent. Prototype;
// If we are already in a 'uber 'function
If (Depth ){
For ( VaR I = D; I > 0 ; I + = 1 ){
V = V. constructor. Prototype;
};
// Obtain the function from the prototype.
Func = V [name];
}
Else {
// Obtain the function to be executed from prototype
Func = Prototype [name];
// If this function belongs to the current prototype
If (Func = This [Name]) {
// The prototype of the parent object is called.
Func = V [name];
}
}
// Record the level where we are located in the inheritance Stack
Depth + = 1 ;
//
RET = Func. Apply ( This , Array. Prototype. Slice. Apply (arguments ,[ 1 ]);
// Resume inheritance Stack
Depth -= 1 ;
Return RET;
});
Return This ;
})
// Only functions that inherit the specific functions of the parent object
Function. Method ( ' Swiss ' , Function (Parent ){
For ( VaR I = 1 ; I < Arguments. length; I ++ ){
VaR Name = Arguments [I];
// Import this method to the prototype of this object
This . Prototype [name] = Parent. Prototype [name];
};
Return This ;
})
Function Person (name ){
This . Name = Name;
}
// Implementation example
Person. Method ( ' Getname ' , Function (){
Return Name;
})
Function User (name, password ){
This . Name = Name;
This . Password = Password;
}
User. inherits (person );
< / SCRIPT>
The following describes the three functions.
1. function. prootype. method: it provides a simple method to associate a function with the prototype of the constructor. The reason is that all constructor functions are functions, therefore, we can obtain the new method "method;
From:Xiao He
2. function. prototype. inherite: This function provides simple object inheritance, and its code mainly calls this in any method. uber ('methodname') is centered, and the Uber method is executed to overwrite the parent object. this is not a built-in part of the Javascript inheritance model.
3. functon. prototype. swiss: this is. an enhanced version of the method () function. It can be used to obtain multiple functions from a single parent object. if you use multiple parent objects, you can obtain available multi-object inheritance.