In object-oriented programming methods, Object Inheritance is essential. How can we implement the Inheritance Mechanism in javascript. Javascript is not a strict object-oriented language, so it is also different in Object Inheritance. We also create a base class Polygon, which represents a Polygon. A Polygon has a common attribute that is the number of sides (sides) and a common method for calculating the area (getAreas ). In this way, the Polygon class looks as defined below: Function Polygon (iSides)
{
This. sides = iSides;
}
Polygon. prototype. getAreas = function ()
{
Return 0;
}
Because the base class cannot determine the area, we return 0 here.
Next we will create a subclass of Triangle, a Triangle. Obviously, this Triangle is inherited from a Polygon, so we need to make this Triangle class inherit from the Polygon class, the getAreas method of the Polygon class must be overwritten to return the area of the triangle. Let's take a look at the implementation in javascript: Function Triangle (iBase, iHeight)
{
Polygon. call (this, 3); // here we use Polygon. call () to call the Polygon constructor. 3 is used as the parameter to indicate that this is a triangle. Because the edges are definite, you do not need to specify the edges in the constructor of the subclass.
This. base = iBase; // bottom of the triangle
This. height = iHeight; // The height of the triangle
}
Triangle. prototype = new Polygon ();
Triangle. prototype. getAreas = function ()
{
Return 0.5 * this. base * this. height; // overwrite the getAreas method of the base class and return the area of the triangle.
}
Refer to the above implementation to define a rectangle: Function Rectangle (iWidth, iHeight)
{
Polygon. call (this, 4 );
This. width = iWidth;
This. height = iHeight;
}
Rectangle. prototype = new Polygon ();
Rectangle. prototype. getAreas = function ()
{
Return this. width * this. height;
}
Now, we have defined a base class and two child numbers. Let's test whether the two child classes work normally: Var t = new Triangle (3, 6 );
Var r = new Rectangle (4, 5 );
Alert (t. getAreas (); // output 9 correctly
Alert (r. getAreas (); // output 20 correct