SoFunction
Updated on 2025-04-07

The construction and inheritance implementation code of js object


<script>
//Define the user object of js
function User(name,age){
=name,
=age,
=function(){
return ;
},
=function(){
return ;
}
}
//Instantiate an object
var use=new User("aa",21);
alert();
alert(());
//js object inheritance
/*
In object-oriented programming methods, object inheritance is essential, so how to implement the inheritance mechanism in javascript. Since javascript is not a strictly object-oriented language, it also shows different in object inheritance. Let's also create a base class Polygon, representing a polygon. A polygon has a common property, which is the number of sides and a common method to calculate the area (getAreas). This way our Polygon class looks like the following definition:
*/
function Polygon(iSides){
= iSides;
}
= function(){
return 0;
}
/*
Because the base class does not determine the area, we return it as 0 here.
Then we create a subclass Triangle, a triangle. Obviously, this triangle needs to be inherited from the polygon, so we need to let the Triangle class inherit the Polygon class and override the getAreas method of the Polygon class to return the area of ​​the triangle. Let's take a look at the implementation in javascript:
*/
function Triangle(iBase, iHeight){
(this,3); //Here we use() to call the Polygon constructor and use 3 as a parameter to indicate that this is a triangle. Because edges are definite, there is no need to specify edges in the constructor of the subclass.
= iBase; //The bottom of the triangle
= iHeight; //The height of the triangle
}
= new Polygon();
= function(){
return 0.5 * *; //Cover the getAreas method of the base class and return the area of ​​the triangle
}

/*
Referring to the above implementation, we define a rectangle:
*/
function Rectangle(iWidth, iHeight){
(this,4);
= iWidth;
= iHeight;
}
= new Polygon();
= function(){
return * ;
}
/*
OK, above we define a base class and two sub-numbers. Let's test whether these two sub-classes work normally:
*/
var t = new Triangle(3,6);
var r = new Rectangle(4,5);
alert(()); //Output 9 instructions are correct
alert(()); //Output 20 description is correct
</script>