//Use prototypal inheritance, and use temporary objects in the middle as the prototype attribute of Child , the prototype attribute of the temporary object points to the prototype of the parent class,
//Prevents all subclasses and parent class prototype attributes from pointing to the same object.
//In this way, when the prototype attribute of the subclass is modified, it will not Affects other subclasses and parent classes
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 closure to simulate private members
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 properties defined by the parent class
this.age = age;
}
extend(Child,Parent); //Inherit Parent
Child.prototype.hello = function() //Override the hello method of the parent class
{
alert(this.getName() "Child");
Parent.prototype.hello.apply(this,arguments); //Call the parent class method with the same name
};
//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