Copy code The code is as follows: <br>//Definition of js user object <br>function User(name,age){ <br>this.name=name, <br>this.age=age, <br>this.getName=function(){ <br>return this.name; <br>}, <br>this.getAge=function(){ <br>return this.age; <br>} <br>} <br>//Instantiate an object<br>var use=new User( "aa",21); <br>alert(use.name); <br>alert(use.getAge()); <br>//js object inheritance<br>/* <br>jb51.net in oriented Object inheritance is essential in object programming methods, so how to implement the inheritance mechanism in javascript? Since JavaScript is not a strictly object-oriented language, object inheritance is also different. Let's also create a base class Polygon to represent a polygon. A polygon has a common attribute which is the number of sides (sides) and a common method to calculate the area (getAreas). In this way, our Polygon class looks like the following definition: <br>*/ <br>function Polygon(iSides){ <br>this.sides = iSides; <br>} <br>Polygon.prototype.getAreas = function(){ <br>return 0; <br>} <br>/* <br>Because the base class cannot determine the area, we return 0 here. <br>Then we create a subclass Triangle, a triangle. Obviously this triangle inherits from polygon, so we need this Triangle class to 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: <br>*/ <br>function Triangle(iBase, iHeight){ <br>Polygon.call(this,3); //Here we use Polygon.call() Call Polygon's constructor and pass 3 as a parameter, indicating that this is a triangle. Because the sides are determined, there is no need to specify the sides in the constructor of the subclass <br>this.base = iBase; //Triangle The base of<br>this.height = iHeight; //The height of the triangle<br>} <br>Triangle.prototype = new Polygon(); <br>Triangle.prototype.getAreas = function(){ <br>return 0.5 * this.base *this.height; //Override the getAreas method of the base class and return the area of the triangle <br>} <br><br>/* <br>Refer to the above implementation, we define another rectangle: <br>*/ <br>function Rectangle(iWidth, iHeight){ <br>Polygon.call(this,4); <br>this.width = iWidth; <br>this.height = iHeight; <br>} <br>Rectangle.prototype = new Polygon(); <br>Rectangle.prototype.getAreas = function(){ <br>return this.width * this.height; <br>} <br>/* <br>Okay, Above we defined a base class and two subclasses, let’s test whether these two subclasses can work properly: <br>*/ <br>var t = new Triangle(3,6); <br>var r = new Rectangle(4,5); <br>alert(t.getAreas()); //Output 9 means it is correct<br>alert(r.getAreas()); //Output 20 means it is correct<br>< /script> <br> </div>