JavaScript objects and inheritance

Source: Internet
Author: User

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 ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.