Hello, everyone! I make milk tea without sugar. A front-end siege lion who likes drinking milk tea (haha, today is another day to touch fish (* ̄))😁😁😁

preface

🙌 recently in the process of learning TS and reviewed the es5 inside the inheritance way, I believe that inheritance is also a lot of interviewers like to ask the knowledge point, especially a pen test questions always want us to write some inheritance method hahaha 😄, here with you review and consolidate

The implementation of JS inheritance

If you want to implement inheritance, of course you need a father, otherwise what is not inheritance parent class:

// Define an animal class

function Animal (name{

  / / property

  this.name = name || 'Animal';

  // Instance method

  this.sleep = function(){

    console.log(this.name + 'Sleeping! ');

  }

  // Instance references attributes

  this.features = [];

}

// Prototype method

Animal.prototype.eat = function({

  console.log(this.name + 'Eating! ');

};

Copy the code

Constructor implementation inheritance (also called object impersonation implementation inheritance)

Use.call() and.apply() to introduce the superclass constructor into the subclass function.

function Cat(name){

  Animal.call(this);

  this.name = name || 'Tom';

}



// Test Code

var cat = new Cat();

console.log(cat.name); //Tom

//instanceof determines if an element is on another element's prototype chain

console.log(cat instanceof Animal); // false

console.log(cat instanceof Cat); // true

cat.sleep() //Tom is sleeping!

cat.eat() Cat. Eat is not a function

Object impersonation can inherit properties and methods from the constructor, but not from the prototype chain

Copy the code

❌ faults:

  • An instance is not an instance of a parent class, only an instance of a subclass
  • You can only inherit instance properties and methods from the parent class, not properties/methods from the parent class prototype
  • Function reuse is not possible, each subclass has a copy of the parent class instance function, affecting performance

    Each subclass has a copy of the parent function’s properties and methods whencatcallAnimalOn the method,AnimalThe inside of thethisPoints to thecat.AnimalThe inside of thethisThe properties and methods of thecatIf each instance of a subclass copies the attributes and methods of its parent class, it will consume a lot of memory. If the methods of the parent class change, the subclass instance cannot update the methods, because it has copied the original method as its own method.

2, prototype chain to achieve inheritance

< span style = “max-width: 100%; clear: both;

function Cat(){

}

Cat.prototype.play = function({

  console.log(this.name + 'Playing! ');

};

Cat.prototype = new Animal();

Cat.prototype.name = 'cat';



// Test Code

var cat = new Cat('zhangsan'); // Shortcoming 4

var cat1 = new Cat('lisi');

cat.name = 'Tom';

cat.features.push('red');

console.log(cat instanceof Animal); //true

console.log(cat instanceof Cat); //true

cat.play() Cat. Prototype = new Animal(); // Play is not a function

cat.eat() // Cat is eating! Solves the shortcoming of constructor implementation inheritance 2 <(* ̄▽ ̄*)/

cat.sleep() // Cat is sleeping!

// Changes to members of the parent instance value type are not affected

console.log(cat.name); // "Tom"

console.log(cat1.name); // "cat"

// A change that refers to a type member of a parent class instance can defect 2 by affecting other subclass instances

console.log(cat.features); // ['red']

console.log(cat1.features); // ['red']



Copy the code

❌ faults:

  • If you want to add a property or method to a subclass, you can do so only in thenew Animal()After that, it cannot be placed in the constructor. As in the code example above, if the new method is placed before changing the orientation of the subclass’s prototype, the new method is uselessprototypeI’m already pointing to the parent class
  • All instances of a subclass share all of the attributes of the parent class. A subclass cannot have its own attributes. If you have multiple instances and one instance changes the value of the reference type of the parent class, then all of the instances will changefeaturesAn array['red'], then the method will change in all instances
  • Multiple inheritance is not possible, because it is changing the direction of the prototype chain and cannot point to multiple parent classes, so it can only be single inheritance
  • When creating a subclass, you cannot pass arguments to the parent class constructor because the attributes and methods of a subclass are invalid after changing the prototype-pointing of the subclass

3. Composite inheritance (composite prototype chain inheritance and borrowed constructor inheritance)

Core: By calling the parent class construction, inherit the attributes of the parent class and retain the advantages of parameter passing, and then by taking the parent class instance as the prototype of the subclass, realize function reuse key: combining the advantages of the above two modes, parameter passing and reuse

function Cat(name){

  Animal.call(this);

  this.name = name || 'Tom';

}

Cat.prototype = new Animal(); // Cat. Prototype = Animal. Prototype;



// Composite inheritance also needs to be fixed to the constructor point.

Cat.prototype.constructor = Cat;



// Test Code

var cat = new Cat();

console.log(cat.name);

console.log(cat.sleep());

console.log(cat instanceof Animal); // true

console.log(cat instanceof Cat); // true

Copy the code

❌ Disadvantages: This method calls the constructor of the parent class twice, generating two instances with the same properties in both the instance and the prototype

Copy inheritance

function Cat(name){

  var animal = new Animal();

  for(var p in animal){

    Cat.prototype[p] = animal[p];

  }

  this.name = name || 'Tom';

}



// Test Code

var cat = new Cat();

console.log(cat.name);

console.log(cat.sleep());

console.log(cat instanceof Animal); // false

console.log(cat instanceof Cat); // true

Copy the code

❌ faults:

  • Cannot get a method whose parent class is not enumerablefor inTo traverseAnimalProperty, such as multi-checkboxcheckedProperties, which are non-enumerable properties
  • Low efficiency, high memory footprint

5. Parasitic Combination Inheritance (recommended)

Core: By parasitic way, the instance attribute of the parent class is cut off, so that when the construction of the parent class is called twice, the method/attribute of the two instances will not be initialized

function Cat(name){

  Animal.call(this);

  this.name = name || 'Tom';

}

(function(){

  // Create a class with no instance methods

  var Super = function(){};

  Super.prototype = Animal.prototype;

  // Use the instance as the prototype of the subclass

  Cat.prototype = new Super();

}) ();



// Test Code

var cat = new Cat();

console.log(cat.name);

console.log(cat.sleep());

console.log(cat instanceof Animal); // true

console.log(cat instanceof Cat); //true

Copy the code

After the language

Hope to see here friends can move a thumbs-up 👍 oh, your support is the biggest encouragement to me 💪💪💪!!