Home Web Front-end JS Tutorial Introduction to various inheritance methods and advantages and disadvantages of js

Introduction to various inheritance methods and advantages and disadvantages of js

May 13, 2017 am 10:51 AM

This article mainly introduces the various ways and advantages and disadvantages of in-depth understanding of JavaScript inheritance. It has certain reference value. Interested friends can refer to it

Written in front

This article explains the various inheritance methods and advantages and disadvantages of JavaScript.

Note:

is the same as "JavaScript In-depth Creating Objects", more like notes.

Hey, let me sigh again: "JavaScript Advanced Programming" is really well written!

1. Prototype chain inheritance

function Parent () {
  this.name = 'kevin';
}

Parent.prototype.getName = function () {
  console.log(this.name);
}

function Child () {

}
Child.prototype = new Parent();

var child1 = new Child();

console.log(child1.getName()) // kevin
Copy after login

Problem:

1.Referenceproperty of type Shared by all instances, for example:


function Parent () {
  this.names = ['kevin', 'daisy'];
}
function Child () {

}

Child.prototype = new Parent();

var child1 = new Child();

child1.names.push('yayu');

console.log(child1.names); // ["kevin", "daisy", "yayu"]

var child2 = new Child();

console.log(child2.names); // ["kevin", "daisy", "yayu"]
Copy after login

2. When creating an instance of Child, parameters cannot be passed to Parent

2. Borrowing Constructor(Classic Inheritance)

function Parent () {
  this.names = ['kevin', 'daisy'];
}

function Child () {
  Parent.call(this);
}

var child1 = new Child();

child1.names.push('yayu');

console.log(child1.names); // ["kevin", "daisy", "yayu"]

var child2 = new Child();

console.log(child2.names); // ["kevin", "daisy"]
Copy after login

Advantages:

1. Avoid reference type properties being shared by all instances

2. You can pass parameters to Parent in Child

For example:

function Parent (name) {
  this.name = name;
}

function Child (name) {
  Parent.call(this, name);
}

var child1 = new Child('kevin');

console.log(child1.name); // kevin

var child2 = new Child('daisy');

console.log(child2.name); // daisy
Copy after login

Disadvantages:

Methods are defined in the constructor, each time Every time you create an instance, a method is created.

3. Combination inheritance

Prototype chain inheritance and classic inheritance are two swords in one.

function Parent (name) {
  this.name = name;
  this.colors = ['red', 'blue', 'green'];
}

Parent.prototype.getName = function () {
  console.log(this.name)
}

function Child (name, age) {

  Parent.call(this, name);
  
  this.age = age;

}

Child.prototype = new Parent();

var child1 = new Child('kevin', '18');

child1.colors.push('black');

console.log(child1.name); // kevin
console.log(child1.age); // 18
console.log(child1.colors); // ["red", "blue", "green", "black"]

var child2 = new Child('daisy', '20');

console.log(child2.name); // daisy
console.log(child2.age); // 20
console.log(child2.colors); // ["red", "blue", "green"]
Copy after login

Advantages: Combining the advantages of prototype chain inheritance and constructors, it is the most commonly used inheritance pattern in JavaScript.

4. Prototypal inheritance

function createObj(o) {
  function F(){}
  F.prototype = o;
  return new F();
}
Copy after login

is the simulation implementation of ES5 Object.create, using the passed in object as the prototype of the created object .

Disadvantages:

Attribute values ​​containing reference types will always share the corresponding value, which is the same as prototype chain inheritance.

var person = {
  name: 'kevin',
  friends: ['daisy', 'kelly']
}

var person1 = createObj(person);
var person2 = createObj(person);

person1.name = 'person1';
console.log(person2.name); // kevin

person1.firends.push('taylor');
console.log(person2.friends); // ["daisy", "kelly", "taylor"]
Copy after login

Note: After modifying the value of person1.name, the value of person2.name has not changed, not because of person1 and person2 has an independent name value, but because person1.name = 'person1', the name value is added to person1, not the name value on the prototype is modified. .

5. Parasitic inheritance

Create a function that is only used to encapsulate the inheritance process. This function is used to enhance the object in some form internally. Finally the object is returned.

function createObj (o) {
  var clone = object.create(o);
  clone.sayName = function () {
    console.log('hi');
  }
  return clone;
}
Copy after login

Disadvantages: Like the borrowed constructor pattern, a method will be created every time an object is created.

6. Parasitic combined inheritance

For the convenience of everyone’s reading, the code of combined inheritance is repeated here:

function Parent (name) {
  this.name = name;
  this.colors = ['red', 'blue', 'green'];
}

Parent.prototype.getName = function () {
  console.log(this.name)
}

function Child (name, age) {
  Parent.call(this, name);
  this.age = age;
}

Child.prototype = new Parent();

var child1 = new Child('kevin', '18');

console.log(child1)
Copy after login

Combined inheritance The biggest disadvantage is that the parent constructor is called twice.

Once when setting the prototype of a subtype instance:

Child.prototype = new Parent();
Copy after login

Once when creating a subtype instance:

var child1 = new Child('kevin', '18');
Copy after login

Recall the simulation implementation of new, in fact, here In the sentence, we will execute:

Parent.call(this, name);
Copy after login

Here, we will call the Parent constructor again.

So, in this example, if we print the child1 object, we will find that both Child.prototype and child1 have an attribute called colors, and the attribute values ​​are ['red', 'blue', 'green'] .

So how can we keep improving and avoid repeated calls this time?

What if we don’t use Child.prototype = new Parent(), but indirectly let Child.prototype access Parent.prototype?

Let’s see how to implement it:

function Parent (name) {
  this.name = name;
  this.colors = ['red', 'blue', 'green'];
}

Parent.prototype.getName = function () {
  console.log(this.name)
}

function Child (name, age) {
  Parent.call(this, name);
  this.age = age;
}
// 关键的三步
var F = function () {};

F.prototype = Parent.prototype;

Child.prototype = new F();


var child1 = new Child('kevin', '18');

console.log(child1);
Copy after login

Finally, let’s encapsulate this inheritance method:

function object(o) {
  function F() {}
  F.prototype = o;
  return new F();
}

function prototype(child, parent) {
  var prototype = object(parent.prototype);
  prototype.constructor = child;
  child.prototype = prototype;
}

// 当我们使用的时候:
prototype(Child, Parent);
Copy after login

To quote the praise of parasitic combined inheritance in "JavaScript Advanced Programming":

The high efficiency of this method reflects that it only calls the Parent constructor once, and therefore avoids creating unnecessary and redundant properties on Parent.prototype. At the same time, the prototype chain remains unchanged; therefore, instanceof and isPrototypeOf can still be used normally. Developers generally believe that parasitic compositional inheritance is the most ideal inheritance paradigm for reference types.

【Related Recommendations】

1. Special Recommendation:"php Programmer Toolbox" V0.1 version Download

2. Free js online video tutorial

3. php.cn Dugu Jiujian (3) - JavaScript video tutorial

The above is the detailed content of Introduction to various inheritance methods and advantages and disadvantages of js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? May 01, 2024 pm 10:27 PM

In function inheritance, use "base class pointer" and "derived class pointer" to understand the inheritance mechanism: when the base class pointer points to the derived class object, upward transformation is performed and only the base class members are accessed. When a derived class pointer points to a base class object, a downward cast is performed (unsafe) and must be used with caution.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How do inheritance and polymorphism affect class coupling in C++? How do inheritance and polymorphism affect class coupling in C++? Jun 05, 2024 pm 02:33 PM

Inheritance and polymorphism affect the coupling of classes: Inheritance increases coupling because the derived class depends on the base class. Polymorphism reduces coupling because objects can respond to messages in a consistent manner through virtual functions and base class pointers. Best practices include using inheritance sparingly, defining public interfaces, avoiding adding data members to base classes, and decoupling classes through dependency injection. A practical example showing how to use polymorphism and dependency injection to reduce coupling in a bank account application.

Detailed explanation of C++ function inheritance: How to debug errors in inheritance? Detailed explanation of C++ function inheritance: How to debug errors in inheritance? May 02, 2024 am 09:54 AM

Inheritance error debugging tips: Ensure correct inheritance relationships. Use the debugger to step through the code and examine variable values. Make sure to use the virtual modifier correctly. Examine the inheritance diamond problem caused by hidden inheritance. Check for unimplemented pure virtual functions in abstract classes.

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

C++ function inheritance explained: When should inheritance not be used? C++ function inheritance explained: When should inheritance not be used? May 04, 2024 pm 12:18 PM

C++ function inheritance should not be used in the following situations: When a derived class requires a different implementation, a new function with a different implementation should be created. When a derived class does not require a function, it should be declared as an empty class or use private, unimplemented base class member functions to disable function inheritance. When functions do not require inheritance, other mechanisms (such as templates) should be used to achieve code reuse.

The AI ​​era of JS is here! The AI ​​era of JS is here! Apr 08, 2024 am 09:10 AM

Introduction to JS-Torch JS-Torch is a deep learning JavaScript library whose syntax is very similar to PyTorch. It contains a fully functional tensor object (can be used with tracked gradients), deep learning layers and functions, and an automatic differentiation engine. JS-Torch is suitable for deep learning research in JavaScript and provides many convenient tools and functions to accelerate deep learning development. Image PyTorch is an open source deep learning framework developed and maintained by Meta's research team. It provides a rich set of tools and libraries for building and training neural network models. PyTorch is designed to be simple, flexible and easy to use, and its dynamic computation graph features make

Detailed explanation of C++ function inheritance: How to understand the 'is-a' and 'has-a' relationship in inheritance? Detailed explanation of C++ function inheritance: How to understand the 'is-a' and 'has-a' relationship in inheritance? May 02, 2024 am 08:18 AM

Detailed explanation of C++ function inheritance: Master the relationship between "is-a" and "has-a" What is function inheritance? Function inheritance is a technique in C++ that associates methods defined in a derived class with methods defined in a base class. It allows derived classes to access and override methods of the base class, thereby extending the functionality of the base class. "is-a" and "has-a" relationships In function inheritance, the "is-a" relationship means that the derived class is a subtype of the base class, that is, the derived class "inherits" the characteristics and behavior of the base class. The "has-a" relationship means that the derived class contains a reference or pointer to the base class object, that is, the derived class "owns" the base class object. SyntaxThe following is the syntax for how to implement function inheritance: classDerivedClass:pu

See all articles