How does JavaScript implement inheritance?

Source: Internet
Author: User

A phone interview question: How does JS implement inheritance?

Functions in JavaScript are omnipotent. In addition to function definitions, functions can also be used for class definitions. The inheritance of JavaScript is also a bit strange. There are no access control modifiers such as public and private, and there is no implement or other specific symbols to demonstrate that it is implemented inheritance. For the inheritance of javascript classes, refer to the following example.

<Script type = "text/javascript"> function Person () {// attribute this. gender = "female"; this. age = 18; this. words = "Silence"; // method this. shouting = function () {alert ("happy! Parent class method ") ;}}// inherits function Programmer () {this. base = Person;} Programmer. prototype = new Person; // Add a new method Programmer to the subclass. prototype. typeCode = function () {alert ("I knocked on the code! IT migrant workers are very unhappy. Subclass method ");} // call the sample function sayHello () {var a = new Programmer (); alert (. gender); // call the attributes of the parent Class. shouting (); // call the method of the parent Class. typeCode (); // call the subclass method} sayHello (); </script>
Simulate classes and inheritance in JavaScript

In the object-oriented language, we use classes to create a custom object. However, everything in JavaScript is an object. How can I create a custom object?

This requires the introduction of another concept-prototype. We can simply regard prototype as a template, and all newly created custom objects are prototype) A copy of (in fact, it is not a copy but a link, but this link is invisible, giving people the feeling that it is a copy ).

Let's take a look at an example of creating a custom object through prototype:

// Constructor function Person (name, sex) {this. name = name; this. sex = sex;} // defines the prototype of Person. attributes in the prototype can be referenced by custom objects. prototype = {getName: function () {return this. name ;}, getSex: function () {return this. sex ;}}

Here we call the Person function a constructor, that is, a function that creates a user-defined object. It can be seen that JavaScript simulates the class function through constructor and prototype.

Code for creating a custom object (instantiation class:

var zhang = new Person("ZhangSan", "man");console.log(zhang.getName()); // "ZhangSan"var chun = new Person("ChunHua", "woman");console.log(chun.getName()); // "ChunHua"

When the code var zhang = new Person ("ZhangSan", "man") is executed, the following items are actually done internally:

  1. Create a blank Object (new Object ()).
  2. Copy the attributes (key-value pairs) in Person. prototype to this empty object (as we mentioned earlier, the internal implementation is not a copy but a hidden link ).
  3. Pass this object to the constructor using the this keyword and execute the constructor.
  4. Assign this object to the variable zhang.

To prove that the prototype template is not copied to an instantiated object, it is a link method. See the following code:

Function Person (name, sex) {this. name = name; this. sex = sex;} Person. prototype. age = 20; var zhang = new Person ("ZhangSan", "man"); console. log (zhang. age); // 20 // overwrite the age attribute zhang in prototype. age = 19; console. log (zhang. age); // 19 delete zhang. age; // After deleting the instance Property age, the property value obtains the console from prototype. log (zhang. age); // 20

This hidden prototype link implemented inside JavaScript is the gentle soil on which JavaScript depends, and is also the basis for simulating inheritance.

How to implement simple inheritance in JavaScript?

The following example creates an Employee class, which inherits all attributes in prototype from Person.

Function Employee (name, sex, employeeID) {this. name = name; this. sex = sex; this. employeeID = employeeID;} // point the prototype of the Employee to an instance of the Person. // because the Person instance can call the method in the Person prototype, therefore, the Employee instance can also call all attributes in the Person prototype. Employee. prototype = new Person (); Employee. prototype. getEmployeeID = function () {return this. employeeID;}; var zhang = new Employee ("ZhangSan", "man", "1234"); console. log (zhang. getName (); // "ZhangSan

The inheritance implementation above is rough and has many problems:

  • It is not appropriate to instantiate the Person when creating the Employee constructor and prototype (hereinafter referred to as the class.
  • The constructor of the Employee class cannot call the constructor of the parent class Person, causing repeated value assignment to the name and sex attributes in the Employee constructor.
  • The functions in Employee override the functions with the same name in Person, and there is no overload mechanism (which is a type problem with the previous one ).
  • The syntax for creating JavaScript classes is too fragmented and not as elegant as that in C #/Java.
  • An error occurred while pointing to the constructor attribute in the implementation.

Related Article

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.