SoFunction
Updated on 2025-03-03

Small examples of js simulation class inheritance


//Use prototype inheritance, use temporary objects as the prototype attribute of Child in the middle, and the prototype attribute of the temporary object points to the prototype of the parent class.
//Prevent all subclass and parent class prototype properties from pointing to a pass-through object.
//In this way, when modifying the prototype properties of the subclass, it will not affect other subclasses and parent classes.
function extend(Child, Parent) {
var F = function(){};
= ;
= new F();
= Child;
= ;
}

function Parent(name)
{
= 123;
= function() {return name;}; // Use closure to simulate private members
= function(value){name=value;};
}
= function(){alert("print!");};
= function()
{
alert(() + "Parent")
};

function Child(name,age)
{
(this, arguments);//Calling the parent class constructor to inherit the properties defined by the parent class
= age;
}
extend(Child,Parent); //Inherit Parent

= function() //Rewrite the parent class hello method
{
alert(() + "Child");

(this,arguments); //Calling the parent class with the same name method as the parent class
};
//Subclass method
= function(){ alert( + "Child doSomething"); };

var p1 = new Child("xhan",22);

var p2 = new Child("xxx",33);

();
();

(); //Subclass method
(); //Presiding method

alert(p1 instanceof Child); //true
alert(p1 instanceof Parent);//true