Home Web Front-end JS Tutorial Why do you need to use JavaScript to implement inheritance? Detailed explanation of examples of several inheritance methods

Why do you need to use JavaScript to implement inheritance? Detailed explanation of examples of several inheritance methods

Jul 20, 2017 pm 03:55 PM
javascript js Why

Why you need to use javascript to implement inheritance

The performance of early PC machines is really not flattering. All the pressure is on the server side, and the client browser is purely for decoration. Coupled with the popular table layout and telephone line Internet access at that time, browsing a web page was very slow; now the Internet era is developing rapidly, personal computer hardware has been greatly improved, and the performance of client browsers is also very disappointing. The model of web development is also quietly changing: the server is no longer as "hard" as before. Instead, the browser should take on as many tasks as possible. In this way, the pressure is distributed to each client. Not only does the enterprise Saving costs also makes web front-end development more interesting - more and more front-end frameworks are emerging, and even many front-end MVC frameworks have emerged. In this context, the role of JavaScript is definitely not just to do some simple verification, send some requests or operate some DOM. It needs to play more roles like front-end routing and business layer, and JavaScript needs to do a lot of logical tasks. , which includes the abstraction of front-end data (i.e. model), and only by using object-oriented thinking can the abstracted data be processed well, so inheritance is very important here.

Now extract a model named Person from the front desk, which has basic attributes name and age. By default, everyone can speak, so the speaking function is placed on the prototype object for each instance to enjoy. . Now for Man, it needs to inherit the basic attributes of Person and add its own unique attributes on this basis.


function Person (name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.say = function(){
  console.log('hello, my name is ' + this.name);
};
function Man() {
  //my own properties
}
Copy after login

Several mainstream inheritance methods:

1. Prototype chain inheritance


function Person (name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.say = function(){
  console.log('hello, my name is ' + this.name);
};
function Man() {
}
Man.prototype = new Person('pursue');
var man1 = new Man();
man1.say(); //hello, my name is pursue
var man2 = new Man();
console.log(man1.say === man2.say);//true
console.log(man1.name === man2.name);//true
Copy after login

This inheritance method is very direct. In order to obtain all attribute methods of Person (instances and prototypes), directly assign the instance of the parent class new Person('pursue') Given the prototype of the subclass, in fact, the subclass instances man1 and man2 themselves are completely empty objects. All attributes and methods have to be found on the prototype chain, so the attributes and methods found are the same.
So it is unrealistic to directly use prototype chain inheritance.

2. Use constructor inheritance


function Person (name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.say = function(){
  console.log('hello, my name is ' + this.name);
};
function Man(name, age) {
  Person.apply(this, arguments);
}
//Man.prototype = new Person('pursue');
var man1 = new Man('joe');
var man2 = new Man('david');
console.log(man1.name === man2.name);//false
man1.say(); //say is not a function
Copy after login

Here the subclass uses apply in the constructor to call the parent class Constructor, so as to achieve the effect of inheriting the properties of the parent class, is much better than directly using the prototype chain. At least each instance has its own share of resources. However, this method can only inherit the instance properties of the parent class, so it cannot be found. Say method, in order to inherit all properties and methods of the parent class, the prototype chain must be modified, thus introducing the combined inheritance method.

3. Combined inheritance


function Person (name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.say = function(){
  console.log('hello, my name is ' + this.name);
};
function Man(name, age) {
  Person.apply(this, arguments);
}
Man.prototype = new Person();
var man1 = new Man('joe');
var man2 = new Man('david');
console.log(man1.name === man2.name);//false
console.log(man1.say === man2.say);//true
man1.say(); //hello, my name is joe
Copy after login

It should be noted that the instance attributes of man1 and man2 actually override the prototype attributes, but There is no need to override the say method on the prototype (because they don't have it), so here man1.say === man2.say still returns true, so you need to be very careful about the prototype property that is not overridden, because it is common to all instances.

4. Parasitic combination inheritance

To be honest, I really don’t know the name of the following form, but it is indeed the most popular and classic one JavaScript inheritance method. In fact, you only need to understand the structure of the prototype object:


function Person (name, age) {
      this.name = name;
      this.age = age;
    }
Person.prototype.say = function(){
  console.log('hello, my name is ' + this.name);
};
function Man(name, age) {
  Person.apply(this, arguments);
}
Man.prototype = Object.create(Person.prototype);//a.
Man.prototype.constructor = Man;//b.
var man1 = new Man('pursue');
var man2 = new Man('joe');
console.log(man1.say == man2.say);
console.log(man1.name == man2.name);
Copy after login

In fact, the only difference between parasitic combination inheritance and the above combination inheritance is the way to construct the prototype object of the subclass Above (a. and b.), the Object.creat(obj) method is used here, which will make a shallow copy of the incoming obj object, similar to:


function create(obj){
  function T(){};
  T.prototype = obj;
  return new T();
}
Copy after login

Therefore, a. The prototype object of the subclass will be well connected with the prototype object of the parent class, instead of directly copying the prototype of the subclass (such as Man.prototype = new Person();), this is just a very violent overwriting of properties. The parasitic combination inheritance method inherits instance attributes and prototype attributes separately, which is more reasonable in implementation.

Note: Code b. will not change the result of instanceof, but for scenarios where construcor is required, this is more rigorous.

The above is the detailed content of Why do you need to use JavaScript to implement inheritance? Detailed explanation of examples of several inheritance methods. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
How to display child categories on archive page of parent categories How to display child categories on archive page of parent categories Apr 19, 2025 pm 11:54 PM

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

Why is the rise or fall of virtual currency prices? Why is the rise or fall of virtual currency prices? Why is the rise or fall of virtual currency prices? Why is the rise or fall of virtual currency prices? Apr 21, 2025 am 08:57 AM

Factors of rising virtual currency prices include: 1. Increased market demand, 2. Decreased supply, 3. Stimulated positive news, 4. Optimistic market sentiment, 5. Macroeconomic environment; Decline factors include: 1. Decreased market demand, 2. Increased supply, 3. Strike of negative news, 4. Pessimistic market sentiment, 5. Macroeconomic environment.

Why does the Spring project cause randomness problems due to circular dependencies when starting? Why does the Spring project cause randomness problems due to circular dependencies when starting? Apr 19, 2025 pm 11:21 PM

Understand the randomness of circular dependencies in Spring project startup. When developing Spring project, you may encounter randomness caused by circular dependencies at project startup...

Why is the return value empty when using RedisTemplate for batch query? Why is the return value empty when using RedisTemplate for batch query? Apr 19, 2025 pm 10:15 PM

Why is the return value empty when using RedisTemplate for batch query? When using RedisTemplate for batch query operations, you may encounter the returned results...

Why can't JavaScript directly obtain hardware information on the user's computer? Why can't JavaScript directly obtain hardware information on the user's computer? Apr 19, 2025 pm 08:15 PM

Discussion on the reasons why JavaScript cannot obtain user computer hardware information In daily programming, many developers will be curious about why JavaScript cannot be directly obtained...

Why does the redisTemplate.opsForList().leftPop() method not support passing in parameters to pop up multiple values ​​at once? Why does the redisTemplate.opsForList().leftPop() method not support passing in parameters to pop up multiple values ​​at once? Apr 19, 2025 pm 10:27 PM

Regarding the reason why RedisTemplate.opsForList().leftPop() does not support passing numbers. When using Redis, many developers will encounter a problem: Why redisTempl...

What is the difference between php framework laravel and yii What is the difference between php framework laravel and yii Apr 30, 2025 pm 02:24 PM

The main differences between Laravel and Yii are design concepts, functional characteristics and usage scenarios. 1.Laravel focuses on the simplicity and pleasure of development, and provides rich functions such as EloquentORM and Artisan tools, suitable for rapid development and beginners. 2.Yii emphasizes performance and efficiency, is suitable for high-load applications, and provides efficient ActiveRecord and cache systems, but has a steep learning curve.

See all articles