JavaScript objects and inheritance
This article records a JavaScript Object definition and inheritance writing method, which is also widely used at present. 1. Define the object (mixed constructor and prototype) // The attribute defines the function Person (name, age, sex) {this In the constructor. name = name; this. age = age; this. sex = sex;} // The method defines Person in the prototype. prototype. hello = function () {alert ("Hello, my name is" + this. name);} Person. prototype. say = function (str) {alert ("This is" + str);} // instance var p = new Person ("Jim", 23, "M"); p. hello (); p. say ("Car"); 2. inherited implementation // defines the subclass attribute function Student (name, age, sex, score) {Person. call (thi S, name, age, sex); // (1) can be considered as a constructor. It initializes this for the inherited parent class attributes. score = score;} // defines the subclass Method Student. prototype = new Person (); // (2) inherits the attributes and methods of the parent class by assigning a value to the prototype constructor of the subclass without any parameters, however, the inherited property values are empty and Student needs to be initialized through (1. prototype. sayScore = function () {alert ("My score is" + this. score);} NOTE: When a and subclass inherit the parent class, the preceding steps (1) and (2) are required. B. If the subclass defines a method with the same name as the parent class, the method with the same name will overwrite the method of the parent class regardless of whether the method parameter with the same name is the same as the parent class, when a subclass object is called, it calls the subclass method. C. when defining a method through prototype, you must use "Object. prototype. methodName = function (){...} otherwise, the subclass cannot directly call the parent class method through the method name. // Instance var s = new Student ("Andy", 22, "F", 100); s. hello (); s. say ("Book"); s. sayScore ();