Use the prototype attribute to simulate class inheritance: first define a Circle class as the parent class, and then define the subclass
PositionCircle.
Js Code
- Function Circle (radius) {// defines the parent class Circle
- This. radius = radius;
- }
- Circle. prototype. area = function () {// defines the method of the parent class. area: calculates the area.
- Return this. radius * this. radius * 3.14;
- }
- Function PositionCircle (x, y, radius) {// defines the class PositionCircle
- This. x = x; // The x coordinate of the attribute.
- This. y = y; // attribute ordinate
- Circle. call (this, radius); // call the method of the parent class, which is equivalent to calling this. Circle (radius) and setting
- // Radius attributes
- }
- PositionCircle. prototype = new Circle (); // you can specify the parent class of PositionCircle as the Circle class.
- Var pc = new PositionCircle (1, 2, 1 );
- Alert (pc. area (); // 3.14
- // The Area Method of the positioncircle class inherits from the circle class, while the area method of the circle class
- // The Area Method inherits the prototype object corresponding to its prototype attribute.
- Alert (PC. radius); // The radius attribute of the positioncircle class inherits from the circle class.
- /*
- Note: Previously we set the prototype attribute of the positioncircle class to point to a circle object,
- Therefore, the prototype attribute of PC inherits the prototype attribute of the circle object, while the constructor of the circle object belongs
- (That is, the constructor attribute of the prototype object corresponding to the Circle object) is directed to the circle.
- Is CIRC.
- */
- Alert (PC. constructor); // circle
- /* For this reason, after we have designed the inheritance relationship of the class, we also need to set the constructor attribute of the subclass. Otherwise, it will point to the parent class.
- Constructor attribute
- */
- PositionCircle. prototype. constructor = PositionCircle
- Alert (pc. constructor); // PositionCircle