Home  >  Article  >  Web Front-end  >  Detailed explanation of the use of the constructor of the inheritance mechanism based on JavaScript and the prototype chain hybrid method_javascript skills

Detailed explanation of the use of the constructor of the inheritance mechanism based on JavaScript and the prototype chain hybrid method_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:34:371041browse

Defects of constructor and prototype implementation inheritance

First, let’s analyze the shortcomings of constructor and prototype chain inheritance methods:

The main problem with constructors (object impersonation) is that the constructor method must be used, and methods defined through prototypes cannot be inherited. This is not the best choice. However, if you use the prototype chain, you cannot use the parameterized constructor. How do developers choose? The answer is simple, use both.

Constructor Prototype Mixing Method

This inheritance method uses constructors to define classes instead of using any prototypes. The best way to create a class is to use constructors to define properties and prototypes to define methods. This method also applies to the inheritance mechanism, using objects to pretend to inherit the properties of the constructor, and using the prototype chain to inherit the methods of the prototype object. Rewrite the previous example using these two methods, the code is as follows:

Copy the code The code is as follows:

function ClassA(sColor) {
this.color = sColor;
}

ClassA.prototype.sayColor = function () {
alert(this.color);
};

function ClassB(sColor, sName) {
ClassA.call(this, sColor);
this.name = sName;
}

ClassB.prototype = new ClassA();

ClassB.prototype.sayName = function () {
alert(this.name);
};


In this example, the inheritance mechanism is highlighted by two lines Code blue implementation. In the first highlighted line of code, in the ClassB constructor, an object is used to pretend to inherit the sColor property of the ClassA class. In the second highlighted line of code, methods of the ClassA class are inherited using the prototype chain. Because this hybrid approach uses the prototype chain, the instanceof operator still works correctly.

The following example tests this code:
Copy the code The code is as follows:

var objA = new ClassA("blue");
var objB = new ClassB("red", "John");
objA.sayColor(); //Output "blue"
objB.sayColor(); //Output "red"
objB.sayName(); //Output "John"

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn