The constructor

The problem with constructors is that they define methods that are created on each instance, so there are no reusable lines, even though the business logic is the same.

The prototype

The problem with prototype chains (just by new)

  • The main problem arises when the stereotype contains reference values. Manipulating a reference value on a stereotype on one instance causes all instances to change.
  • The second problem is that when a subtype is instantiated, arguments cannot be passed to the constructor of the parent type

Embezzling constructors (by using the call()(or apply()) method)

function SuperType() {
this.colors = ["red", "blue", "green"];
}
 function SubType() {
    SuperType.call(this);
}
let instance1 = new SubType(); 
instance1.colors.push("black"); 
console.log(instance1.colors); // "red,blue,green,black"
let instance2 = new SubType(); 
console.log(instance2.colors); // "red,blue,green"
Copy the code

Compared with the prototype chain, there are two advantages:

  1. At supertype.call (this), all the initialization code in SuperType() is run, resulting in each instance having its colors attribute;
  2. Because call or apply is used, we can pass values to the parent constructor through the subclass constructor (as follows) :
function SuperType(name){ this.name = name; } function SubType() {// SuperType. Call (this, "Nicholas"); // Instance attribute this.age = 29; } let instance = new SubType(); console.log(instance.name); // "Nicholas"; console.log(instance.age); / / 29Copy the code

Problem with embezzling constructors

  • You can only use the data on the parent class prototype, you can’t use the method on the prototype, so if you want to have your own method to use, you have to define your own, others can’t use, so you can’t use it alone

Composite inheritance (a combination of stereotype chains and stolen constructors)

The basic idea is to use stereotype chains to inherit methods on stereotypes, and to inherit instance properties by stealing constructors. This allows methods to be defined on prototypes for reuse and each instance to have its own properties.
this.name = name; this.colors = ["red", "blue", "green"]; } SuperType.prototype.sayName = function() { console.log(this.name); }; Function SubType(name, age){// Inherit supertype. call(this, name); this.age = age; } // subtype.prototype = new SuperType(); SubType.prototype.sayAge = function() { console.log(this.age); }; let instance1 = new SubType("Nicholas", 29); instance1.colors.push("black"); console.log(instance1.colors); // "red,blue,green,black" instance1.sayName(); // "Nicholas"; instance1.sayAge(); // 29 let instance2 = new SubType("Greg", 27); console.log(instance2.colors); // "red,blue,green" instance2.sayName(); // "Greg"; instance2.sayAge(); / / 27Copy the code