Alibaba technology article sharing JavaScript inheritance mechanism implementation _javascript skill

Source: Internet
Author: User

JavaScript as a scripting language, at the beginning of design did not take into account the object-oriented characteristics. Even in today's modern-day browser era, JavaScript frameworks/libraries have sprung up, and there is no class keyword in JavaScript. If you want to write a class, you have to use the function, as for inheritance, overload or something, do not expect.

But, did not inherit, the day how to live? Is it possible to copy all the common logic and achieve the lowest level of code reuse?

The answer is of course--no, so we have to achieve our own inheritance!

Goal

The most critical goal, of course, is inheritance--the subclass automatically owns all the public properties and methods of the parent class.

Support for instanceof, for example, C is an instance of a subclass, and P is the parent class, and C instanceof p should return true.

Second, you should be able to override (Override) The method of the parent class, and in the subclass's method, you can easily invoke the same method as the parent class.

As for the overload (overload), it cannot be implemented because of the language characteristics of JavaScript (which cannot have a method of the same name, even if their argument list is not the same).

Design and implementation

JavaScript objects have a very important attribute--__proto__, which is the prototype. A prototype is also an object, and all of it can have its own prototype, thus forming a prototype chain. When you call a method of an object, or read a property of that object, the JavaScript executor does this:

1, first to the object to find the corresponding method or attribute, if not found,
2, to find the prototype of the object, if you can not find,
3, to prototype the prototype inside find
4 、...
5, until finally found the object of the prototype, if not yet return undefined
As shown in the following illustration:


This feature of the prototype chain is similar to inheritance, so naturally we can use it to implement the inheritance mechanism. And the support of prototype chain to instanceof makes it a good choice.

We define the Extend function, which accepts two arguments, the first is the parent class, and the second is a subclass, as follows:

function Extend (ParentClass, childclass) {
  ...
  return childclass;
}

This function handles the subclass and returns the subclass. The logic of processing is as follows:

Build a prototype chain

By connecting the prototype chain of a subclass with the prototype chain of the parent class, the subclass can automatically have the methods and properties of the parent class:

var pp = parentclass.prototype,
  cp = Childclass.prototype;
function T () {};
T.prototype = pp;
Childclass.prototype = new T ();

In order to connect to the prototype chain, you need to create an instance of the parent class and assign it to the stereotype properties of the child class. But we do not want to instantiate the parent class in the Extend method, so we introduce a middle class T to solve the problem.

Implementation overrides

After the prototype chain is established, the methods and attributes on the original subclass prototype are also required to be preserved:

Method

If the parent class has a method of the same name, we use a closure to hold a reference to the parent class method and the subclass method. Then, modify the reference of the method in the new prototype to point to a new function. In this function, we create a temporary attribute super, point it to the parent class method, and call the subclass method, so that the parent class method can be invoked through This.super in the subclass method:

Childclass.prototype[name] = (function (pm, CM) {return
  function () {
    var _super = this.super;
    This.super = PM;
    var result = Cm.apply (this, arguments);
    This.super = _super;
    return result
  };
}) (Pp[name], cp[name]);

Property

For attributes, there is no overriding problem, so simply adding the attributes from the original prototype of the subclass to the new prototype:

Childclass.prototype[name] = Cp[name];

Construction device

In order for subclasses to have access to the constructor of the parent class, we assign the parent class to the Super attribute of the subclass:

Childclass.super = ParentClass;

How to use

Suppose we want to design a management system that involves customers, workers, and managers. Abstract the commonality of customers and employees, we get people (people), and then abstract the common denominator of workers and managers to employees (employee). So we get class three structure:


The code to implement this design is as follows:

function people (FirstName, LastName) {
  this.firstname = FirstName;
  This.lastname = LastName;
}

function Employee (firstname, LastName, company) {
  Employee.super.apply (this, arguments);
  This.company = Company;
}

function Manager (firstname, LastName, Company, title) {
  Manager.super.apply (this, arguments);
  this.title = title;
}

We want to have a description for everyone, people is the surname + name, the employee after the surname + name, also includes the company name, and the manager after the employee's description, also includes the position. The code is as follows:

People.prototype.summary = function () {return
  This.firstname + "" + This.lastname;
};

Employee.prototype.summary = function () {return
  This.super.call (this) + "," + This.company;
};

Manager.prototype.summary = function () {return
  This.super.call (this) + "," + This.title;
};

After all member methods have been defined, declaring the inheritance of the class (you must first define the method and then declare the inheritance of the class) cannot use This.super to invoke the parent class method in the Method! ):

Extend (people, Employee);
Extend (Employee, Manager);

The use of these classes is simpler, direct new is good:

var people = new People ("Alice", "Dickens");
var employee = new Employee ("Bob", "Ray", "Alibaba");
var manager = new manager ("Calvin", "Klein", "Alibaba", "Senior Manager");
Console.log (People.summary ()); Alice Dickens
Console.log (Employee.summary ());//bob Ray, Alibaba
console.log (Manager.summary ()); Calvin Klein, Alibaba, Senior Manager

This article is good, then give a praise bar!

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.