Inheritance is an essential feature of object-oriented systems, but javascript does not have an inherited conceptual mechanism, but we can implement this function on our own.
The Code is as follows:
Var JsObject ={}| | new Object ();
JsObject. extend = function (subClass, superClass ){
// First determine whether the subClass has been defined. If not defined, the class is redefined.
If (typeof subClass = "undefined") subClass = function (){};
// If the parent class superClass is a class, it is converted to an object
If (typeof superClass = "function") superClass = new superClass ();
// Traverse the attributes and methods in the parent class superClass object
For (var p in superClass)
{
/* Copy the attributes and methods in the parent class superClass object to the prototype object of the subclass,
Therefore, subclass has all the features of the parent class, that is, inheritance */
SubClass. prototype [p] = superClass [p];
}
Return subClass;
};
Function Student ()
{
This. name = "James ";
This. updateName = function (name ){
This. name = name;
}
}
Function Class1 ()
{
This. sex = "male ";
This. updateSex = function (sex ){
This. sex = sex;
}
}
// Define the class Class1 to inherit the Student class
Class1 = JsObject. extend (Class1, Student );
Var obj = new Class1 ();
Alert (obj. sex );
Alert (obj. name );
Obj. updateSex ("female ");
Obj. updateName ("Mary ");
Alert (obj. sex );
Alert (obj. name );
The results show that male, Michael, female, and Mary