CopyCode The Code is as follows: // use prototype inheritance, and use a temporary object as the Child prototype property in the middle. The prototype property of the temporary object then points to the prototype of the parent class,
// Prevent all subclass and parent class prototype attributes from pointing to an object.
// When the prototype attribute of the subclass is modified, other subclasses and parent classes will not be affected.
Function extend (child, parent ){
VaR F = function (){};
F. Prototype = parent. Prototype;
Child. Prototype = new F ();
Child. Prototype. constructor = child;
Child. base = parent. Prototype;
}
Function parent (name)
{
This. AA = 123;
This. getname = function () {return name;}; // use a closure to simulate a private member
This. setname = function (value) {name = value ;};
}
Parent. Prototype. Print = function () {alert ("print! ");};
Parent. Prototype. Hello = function ()
{
Alert (this. getname () + "parent ")
};
Function child (name, age)
{
Parent. Apply (this, arguments); // call the parent class constructor to inherit the attributes defined by the parent class
This. Age = age;
}
Extend (child, parent); // inherits parent
Child. Prototype. Hello = function () // rewrite the hello method of the parent class
{
Alert (this. getname () + "child ");
Parent. Prototype. Hello. Apply (this, arguments); // call the method with the same name as the parent class
};
// Subclass Method
Child. Prototype. dosomething = function () {alert (this. Age + "Child dosomething ");};
VaR p1 = new child ("xhan", 22 );
VaR P2 = new child ("XXX", 33 );
P1.hello ();
P2.hello ();
P1.dosomething (); // subclass Method
P1.print (); // parent class Method
Alert (P1 instanceof child); // true
Alert (P1 instanceof parent); // true