Copy codeThe 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