JavaScript Difficulty Series (VI): Prototype chain and inheritance

Source: Internet
Author: User

Classes and constructors

Use constructors to define classes in JS:

function Range(from, to) {    this.from = from    this.to = to}Range.prototype.includes = function(x) {    return this,from <= x && x <= this.to}Range.prototype.toString = function() {    return this.from + ‘...‘ + this.to}var r1 = new Range(1, 3)console.log(r.includes(2))  // trueconsole.log(r.toString())  // 1...3

The code above declares a range constructor, generates a class range, and uses the new keyword to generate the instance object R1.

New Range (1, 3) This expression does the following things:

var obj = {}obj.__proto__ = Range.prototypevar result = Range.call(obj, 1, 3)return typeof result === ‘obj‘ ? result : obj

The first step creates a new empty object.
The second step is to set the __proto__ of the new object to the prototype of range, which is the prototype of range.
The third step is to assign a value to the property of the new object by passing a parameter to the range constructor.
The fourth step detects whether the range constructor returns a new object, returns it if there is one, and returns obj if there is no property assigned to it.
In fact, the new keyword is a syntactic sugar, similar to a function, we use it, it is equivalent to write the above four lines of code.

When new is finished, we can say that the R1 object is an instance of the range class, but the constructor is only the public identity of the class and is not a unique identity. That is to say, the prototype property of two different constructors can point to the same prototype object, so they create instances that belong to the same class. So the prototype object is the unique identity of the class, and the method of detecting the type described below is based on whether the instance object inherits from a prototype object, rather than detecting which constructor initializes the instance object.
A total of three kinds of detection objects of the class technology:

    1. o instanceof Range
      If o inherits from or indirectly inherits from Range.prototype, then the result of the above expression is true
    2. Range.prototype.isPrototypeOf (o)
      If o inherits from or indirectly inherits from Range.prototype, then the result of the above expression is true
      *****
Prototype chain and inheritance

JS in the implementation of inheritance is mainly based on the prototype chain to achieve. The basic idea is to make the prototype object of the subtype equal to the instance of the parent type. In general, there are three ways to implement inheritance: Prototype chain inheritance, borrowing constructor inheritance, and combining inheritance.

Prototype chain inheritance

function super() {    this.colors = ["red", "blue", "green"];}function sub() {}sub.prototype = new super();var instance1 = new sub();instance1.colors.push("black");alert(instance1.colors); //"red,blue,green,black"var instance2 = new sub();alert(instance2.colors); //"red,blue,green,black"

The code above assigns the prototype object of the sub to the instance object of the Super parent class, and the properties of the super instance become the prototype properties of the sub. But there are two questions:

    1. If a reference type value exists on the Super instance property, the sub's prototype object property will also have the same reference type value. All instance objects of a sub then share the reference type property on their prototype object. Changes to Instance1 in the code above affect Instance2.
    2. When you create an instance of a sub type, you cannot pass arguments to the super type's constructor. That is, the super type constructor can use only the default value if it needs to use a parameter.

Borrowing constructors
In order to solve the problem caused by the reference type value inherited by the prototype chain, a technique called borrowing a constructor (classic inheritance) appears. The basic idea is to call the constructor of the parent type inside the subtype constructor.

function super(name) {    this.colors = ["red", "blue", "green"];    this.name = name;}function sub() {    super.call(this, "jaja");}var instance1 = new sub();instance1.colors.push("black");alert(instance1.colors); //"red,blue,green,black"alert(instance1.name); // "jaja"var instance2 = new sub();alert(instance2.colors); //"red,blue,green"

Although this inheritance method "Inherits" the instance properties in the parent class's constructor, it cannot inherit the methods defined in the parent class's prototype. Inheriting only the attributes in the constructor and unable to re-use the parent class's prototype method, you cannot be called a true inheritance.

Combining inheritance
In order to play the advantages of the above two inheritance methods, the technical staff also invented the combination of inheritance. The main idea is to use the prototype chain to implement the inheritance of the prototype properties and methods, and to implement the inheritance of instance attributes by borrowing constructors.

function super() {    this.colors = ["red", "blue", "green"];}function sub() {    super.call(this);}sub.prototype = new super();sub.prototype.constructor = sub;var instance1 = new sub();instance1.colors.push("black");alert(instance1.colors); //"red,blue,green,black"var instance2 = new sub();alert(instance2.colors); //"red,blue,green"

Composite inheritance can be seen as an enhancement of the inheritance of the prototype chain, which differs from the prototype chain inheritance in that the constructor of the parent class is referenced in the constructor of the subclass. This way, even if you use Sub.prototype = new super () to inherit the reference type value of the parent class, the value of the reference type of super is covered by the constructor of the sub with the instance property, and the Super Prototype object's method remains not overwritten.

JavaScript Difficulty Series (VI): Prototype chain and inheritance

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.