惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
News and Events Feed by Topic
GbyAI
GbyAI
博客园 - Franky
宝玉的分享
宝玉的分享
Blog — PlanetScale
Blog — PlanetScale
Google DeepMind News
Google DeepMind News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
人人都是产品经理
人人都是产品经理
Microsoft Azure Blog
Microsoft Azure Blog
The Register - Security
The Register - Security
腾讯CDC
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
I
InfoQ
The Cloudflare Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Engineering at Meta
Engineering at Meta
MongoDB | Blog
MongoDB | Blog
有赞技术团队
有赞技术团队
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
F
Full Disclosure
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Vercel News
Vercel News
博客园 - 【当耐特】
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Schneier on Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Project Zero
Project Zero
量子位
M
MIT News - Artificial intelligence
Stack Overflow Blog
Stack Overflow Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
美团技术团队
Attack and Defense Labs
Attack and Defense Labs
C
Cybersecurity and Infrastructure Security Agency CISA
T
The Blog of Author Tim Ferriss
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
罗磊的独立博客
P
Proofpoint News Feed
Schneier on Security
Schneier on Security
Spread Privacy
Spread Privacy
S
SegmentFault 最新的问题
L
LINUX DO - 最新话题
Simon Willison's Weblog
Simon Willison's Weblog
爱范儿
爱范儿
博客园 - 聂微东
A
About on SuperTechFans
PCI Perspectives
PCI Perspectives
D
Docker

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
Prototypal Inheritance in JavaScript
Dmitri Pavlutin · 2020-11-03 · via Dmitri Pavlutin Blog

Understanding prototypal inheritance is the key to understanding how objects inherit properties in JavaScript.

This concept is also asked often during JavaScript interviews.

In this post, I'll help you understand prototypal inheritance.

1. Introduction

JavaScript has only primitives types, null, undefined, and objects. A big world of objects. In JavaScript, contrary to languages like Java or PHP, there’s no concept of class that serves as a template to create objects.

Let's also recall that an object is a composable structure having properties: key and value pairs. For example, the following object cat contains 2 properties:


const cat = { sound: 'Meow!', legs: 4 };


Since I'd like to reuse legs property in other objects (on dogs, for example), let's extract legs property into a specialized object pet:


const pet = { legs: 4 };

const cat = { sound: 'Meow!' };


That looks better.

But how can I connect cat with pet? I can make pet a prototype object for cat!

2. The prototype object

In JavaScript, an object can inherit properties of another object. The object from where the properties are inherited is named prototype.

Following the example, you can make pet a prototype of cat which will then inherit legs property.

When creating an object using the object literal, you can use the special property __proto__ to set the prototype of the created object.

Let's use __proto__ and make pet the prototype of cat:


const pet = { legs: 4 };

const cat = { sound: 'Meow!', __proto__: pet };

cat.legs; // => 4


cat object now inherits legs from the prototype pet. Now you can use the property accessor cat.legs that evaluates to 4.

sound property, on the other side, is an own property because it's defined directly on the object.

Inherited property from the prototype in JavaScript

The essence of prototypal inheritance in JavaScript: objects can inherit properties from other objects — the prototypes.

You're probably wondering: why the need for inheritance in the first place?

Inheritance solves the problem of data and logic duplication. By inheriting, objects can share properties and methods.

For example, you could easily reuse legs property to create more pets:


const pet = { legs: 4 };

const cat = { sound: 'Meow!', __proto__: pet };

const dog = { sound: 'Bark!', __proto__: pet };

const pig = { sound: 'Grunt!', __proto__: pet };

cat.legs; // => 4

dog.legs; // => 4

pig.legs; // => 4


cat, dog, and pig all reuse the property legs.

Note: __proto__ is deprecated, but I'm using it for simplicity. In production code Object.create() is recommended.

2.1 Own vs inherited property

If an object has an own property and an inherited property with the same name, then JavaScript always picks the own property.

In the following example chicken object has an own property legs, but also inherits a property with the same name legs:


const pet = { legs: 4 };

const chicken = { sound: 'Cluck!', legs: 2, __proto__: pet };

chicken.legs; // => 2


chicken.legs evaluates to 2. JavaScript picks the own property legs (which is 2) over the inherited legs (which is 4).

Own vs inherited property in JavaScript

If you delete the own property, then JavaScript picks the inherited one!


const pet = { legs: 4 };

const chicken = { sound: 'Cluck!', legs: 2, __proto__: pet };

chicken.legs; // => 2

delete chicken.legs;

chicken.legs; // => 4


3. The implicit prototype

When you create an object, and no prototype is explicitly set, JavaScript assigns an implicit prototype specific to the type of object you've created.

Let's look again at the pet object:


const pet = { legs: 4 };

pet.toString(); // => `[object Object]`


pet has just one property legs, however, you can invoke the method pet.toString(). Where did toString() come from?

When you've created the pet object, JavaScript has assigned to it an implicit prototype object. From this implicit prototype pet inherits toString() method:


const pet = { legs: 4 };

const petPrototype = Object.getPrototypeOf(pet);

pet.toString === petPrototype.toString; // => true


petPrototype is the implement (aka default) prototype of the created object.

Object.getPrototypeOf(object) is an utility function that returns the prototype of an object.

4. The prototype chain

What's interesting about prototypes is that they can be connected in a chain. An object can have a prototype, and that prototype by itself can have another prototype... and so on in chain.

Let's go deeper and create an object tail, making it also a prototype of pet:


const tail = { hasTail: true };

const pet = { legs: 4, __proto__: tail };

const cat = { sound: 'Meow!', __proto__: pet };

cat.hasTail; // => true


cat inherits the property legs from its direct prototype pet. But cat also inherits hasTail from the prototype of its prototype — tail!

Prototypes chain in JavaScript

When accessing a property myObject.myProp, JavaScript looks for myProp inside the own properties of myObject, then in the prototype of the object, then in the prototype's prototype, and so on until it encounters null as the prototype.

In other words, JavaScript looks for inherited properties in the chain of prototypes.

5. But JavaScript has classes!

You may be confused regarding the statement that JavaScript has only objects. You've probably already used the class keyword in JavaScript!

For example, you can write a class Pet:


class Pet {

legs = 4;

constructor(sound) {

this.sound = sound;

}

}

const cat = new Pet('Moew!');

cat.legs; // => 4

cat instanceof Pet; // => true


and create a cat when instantiating the class.

The secret is that class syntax in JavaScript is syntactic sugar on top of prototypal inheritance.

The above class-based code snippet is equivalent to the following:


const pet = { };

function CreatePet(sound) {

return { sound, __proto__: pet, legs: 4 };

}

CreatePet.prototype = pet;

const cat = CreatePet('Moew!');

cat.legs; // => 4

cat instanceof CreatePet; // => true


CreatePet.prototype = pet assignment is necessary to make cat instanceof CreatePet evaluate to true.

When working with class-es you can completely forget about prototypes.

6. Summary

In JavaScript, objects inherit properties from other objects — the prototypes. That's the idea of prototypal inheritance.

JavaScript looks for inherited properties in the prototype of the object, but also in the prototype of the prototype, and so on in the chain of prototypes.

While prototypal inheritance seems clumsy at first, when understanding it you could enjoy its simplicity and possibilities. Objects inherit properties from objects — what could be simpler?

Have questions about prototypal inheritance? Ask in a comment below!