search
HomeWeb Front-endJS TutorialParsing javaScript's prototypal inheritance

The essence of inheritance: reuse

Before discussing the prototypal inheritance of javaScript, you might as well think about why we need to inherit?

Consider a scenario, if we have two objects , some of their properties are the same, and the other properties are different. Usually a good design solution is to extract the same logic for reuse.

Take two classmates xiaoMing liLei as an example. The two classmates have their own names and will introduce themselves. Abstracted as a program object, it can be represented as follows.

var xiaoMing = {
  name : "xiaoMing",
  hello : function(){
    console.log( 'Hello, my name is '+ this.name + '.');
  }
}

var liLei = {
  name : "liLei",
  hello : function(){
    console.log( 'Hello, my name is '+ this.name  + '.');
  }
}

Students who have used java may first think of using Object-oriented to solve this problem. Create a Person class and instantiate two objects, xiaoMing and liLei. In ES6, there is also a concept similar to classes in Java: class .

The following uses ES6 syntax and uses object-oriented ideas to reconstruct the above code.

class Person {
  constructor(name){
    this.name = name
  }

  hello(){
    console.log(this.name);
  }
}

var xiaoMing = new Person('xiaoMing');
var liLei = new Person('liLei');

You can see that using class to create objects achieves the purpose of reuse. The logic it is based on is that if two or more objects have similar structures and functions, a template can be abstracted and multiple similar objects can be copied according to the template.

Using classes to create objects is like a bicycle manufacturer reusing the same blueprints over and over again to build a large number of bicycles.

Of course there is more than one solution to the reuse problem. Traditional object-oriented classes are just one of the solutions. Now it is the turn of our protagonist "prototypal inheritance" to appear, which solves the problem of reuse from another angle.

Principle of prototypal inheritance

Prototype object

The object in javaScript consists of two parts, a collection of ordinary properties, and prototype properties.

var o = {
  a : 'a',
  ...
  proto: prototypeObj
}

Ordinary attributes refer to a; Prototype attributes refer to proto. This was not part of the specification. Later, chrome exposed the underlying properties of the language through proto, which was gradually accepted by everyone and was added to the ES6 specification. The value of o.proto prototypeObj is Prototype Object. The prototype object is actually an ordinary object. The reason why it is called a prototype object is just because it is the value pointed by the prototype attribute.

The prototype object is special because it has an ability that ordinary objects do not have: sharing its properties with other objects.

In the ES6 specification, it is defined as follows:

object that provides shared properties for other objects

Attribute read operation

Go back to the original example and see how to use prototypal inheritance to achieve reuse Purpose.

var prototypeObj = {
  hello: function(){
    console.log( 'Hello, my name is '+ this.name  + '.');
  }
  // ...
}

var xiaoMing = {
  name : "xiaoMing",
  proto : prototypeObj
}

var liLei = {
  name : "liLei",
  proto :  prototypeObj
}

xiaoMing.hello(); // Hello, my name is xiaoMing.
liLei.hello();  // Hello, my name is liLei.

xiaoMing liLei The object does not directly have the hello attribute (method), but it can read the attribute (execute the method). Why is this?

Imagine a scenario where you are doing math homework and encounter a difficult question that you cannot do. And you have a good brother who is very good at mathematics. You go to ask him for help and solve this problem.

There is no hello attribute on the xiaoMing object, but it has a good brother, prototypeObj. For attribute reading operations, if the hello attribute is not found on xiaoMing, it will ask its brother prototypeObj. So the hello method will be executed.

Prototype Chain

It’s still an example of doing math problems. Your math question is difficult and your brother doesn't have the answer. He recommends that you ask another classmate. That way you won't ask anymore until you have the answer or there's no one left to ask. It's like there is an invisible chain linking you with your classmates.

In JS, the read operation is chained layer by layer through proto, which is called the prototype chain.

var deepPrototypeObj = {
  hello: function(){
    console.log( 'Hello, my name is '+ this.name  + '.');
  }
  proto : null
}

var prototypeObj = {
  proto : deepPrototypeObj
}

var xiaoMing = {
  name : "xiaoMing",
  proto : prototypeObj
}

var liLei = {
  name : "liLei",
  proto :  prototypeObj
}

xiaoMing.hello(); // Hello, my name is xiaoMing.
liLei.hello();  // Hello, my name is liLei.

Implementation of prototypal inheritance

In the above example, prototypal inheritance is implemented by directly modifying the proto attribute value. But in actual production,

The alternative is to use the Object.create() method.

Calling the Object.create() method will create a new object and specify the prototype object of the object as the first parameter passed in.

Let’s change the above example.

var prototypeObj = {
  hello: function(){
    console.log( 'Hello, my name is '+ this.name  + '.');
  }
  // ...
}

var xiaoMing = Object.create(prototypeObj);
var liLei = Object.create(prototypeObj);

xiaoMing.name = "xiaoMing";
liLei.name = "liLei";

xiaoMing.hello(); // Hello, my name is xiaoMing.
liLei.hello();  // Hello, my name is liLei.

The author of You-Dont-Know-JS gave this implementation of prototypal inheritance a very interesting name OLOO (objects-linked-to-other-objects). The advantages of this implementation It does not use the concept of any class, only object, so it is very consistent with the characteristics of JavaScript.

Because there are no classes in JS, only object.

Unfortunately, there are too many programmers who like classes, so the class concept was added in ES6. The next article will talk about the implementation principle of class in JS

Summary

Class creates objects to achieve the purpose of reuse. The logic it is based on is that two or more objects have similar structures and functions, and a template can be abstracted, and multiple similar objects can be copied according to the template. It's like bike manufacturers reusing the same blueprints over and over again to build lots of bikes.

Using prototypal inheritance can also achieve the purpose of reuse. The logic it is based on is that two or more objects have some shared attributes. The shared attributes can be abstracted to another independent public object. Through special prototype attributes, the public objects and ordinary objects can be linked and reused. Attribute reading (writing) rules are traversed and searched to realize attribute sharing.


The above is the detailed content of Parsing javaScript's prototypal inheritance. For more information, please follow other related articles on the PHP Chinese website!

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
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

How to send notifications before a task starts in Quartz?How to send notifications before a task starts in Quartz?Apr 04, 2025 pm 09:24 PM

How to send task notifications in Quartz In advance When using the Quartz timer to schedule a task, the execution time of the task is set by the cron expression. Now...

See all articles

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)