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

推荐订阅源

G
Google Developers Blog
S
Schneier on Security
The Hacker News
The Hacker News
P
Proofpoint News Feed
Spread Privacy
Spread Privacy
L
LINUX DO - 热门话题
L
Lohrmann on Cybersecurity
I
Intezer
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Schneier on Security
Schneier on Security
Security Latest
Security Latest
AWS News Blog
AWS News Blog
B
Blog RSS Feed
Microsoft Security Blog
Microsoft Security Blog
有赞技术团队
有赞技术团队
博客园 - 叶小钗
The Last Watchdog
The Last Watchdog
O
OpenAI News
月光博客
月光博客
Hacker News: Ask HN
Hacker News: Ask HN
阮一峰的网络日志
阮一峰的网络日志
S
Security @ Cisco Blogs
Google Online Security Blog
Google Online Security Blog
云风的 BLOG
云风的 BLOG
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Latest news
Latest news
P
Palo Alto Networks Blog
Last Week in AI
Last Week in AI
M
MIT News - Artificial intelligence
Google DeepMind News
Google DeepMind News
P
Proofpoint News Feed
C
CERT Recently Published Vulnerability Notes
Apple Machine Learning Research
Apple Machine Learning Research
U
Unit 42
PCI Perspectives
PCI Perspectives
博客园 - 聂微东
SecWiki News
SecWiki News
宝玉的分享
宝玉的分享
Forbes - Security
Forbes - Security
H
Heimdal Security Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Troy Hunt's Blog
博客园 - 三生石上(FineUI控件)
Application and Cybersecurity Blog
Application and Cybersecurity Blog
罗磊的独立博客
WordPress大学
WordPress大学
D
Darknet – Hacking Tools, Hacker News & Cyber Security

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 Prototypal Inheritance in JavaScript 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 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
Own and Inherited Properties in JavaScript
Dmitri Pavlutin · 2020-05-25 · via Dmitri Pavlutin Blog
Post cover

In JavaScript, contrary to other programming languages like Java or Python, there's no template (e.g. class) concept for creating objects.

Every JavaScript object links to another object named prototype, from which the object inherits properties.

In this post, I'll describe the difference between own and inherited properties. It's a good way to understand the slightly unusual inheritance mechanism of JavaScript.

1. Own properties

An own property is a property defined directly on the object.

Let's define a plain JavaScript object with one property:


const myObject = {

myProp: 'Value'

};

myObject.myProp; // => 'Value'


myObject is a plain JavaScript object. The property myProp is defined directly on myObject, being an own property.

To list the own properties of an object use the built-in utility function Object.getOwnPropertyNames(object).

Let's list the own properties of myObject:


const myObject = {

myProp: 'Value'

};

Object.getOwnPropertyNames(myObject); // => ['myProp']


Object.getOwnPropertyNames(myObject) returns an array having one own property name: ['myProp'].

2. Inherited properties

An inherited property is a property the object inherits from the prototype object.

Every object in JavaScript links to an object, the prototype, from which it inherits properties.

Let's use again myObject. This time let's access a property that you haven't defined upon myObject directly:


const myObject = {

myProp: 'Value'

};

myObject.toString; // => function() {...}


The property accessor myObject.toString evaluates to a function.

toString is an inherited property. In other words, myObject inherits toString property from its prototype object.

When JavaScript evaluates the expression myObject.toString, first, it tries to find the property toString within the own properties - however it cannot find one (myObject has just one own property myProp). Then JavaScript looks inside the prototype object of myObject, and finally finds a property toString.

Inherited toString property of myObject equals to the same property access directly from the prototype object:


const myObject = {

myProp: 'Value'

};

const myObjectProto = Object.getPrototypeOf(myObject);

myObject.toString === myObjectProto.toString; // => true


Where Object.getPrototypeOf(object) is an utility function that returns the object's prototype.

3. Prototype as a source of inherited properties

When I was trying to understand the prototypal inheritance in JavaScript, I was thinking that the prototype object is a complex or special God object. But it's much simpler.

Think about the prototype object as a source of inherited properties for an object.

4. Own vs inherited

Let's slightly modify myObject and define a method toString directly on it:


const myObject = {

myProp: 'Value',

toString() {

return `[object MyObject]`;

}

};

const myObjectProto = Object.getPrototypeOf(myObject);

myObject.toString === myObjectProto.toString; // => false


Because myObject has an own property toString, the object does no longer inherit toString from the prototype object.

When an object has an own property and inherits a property with the same name, the own property takes precedence over the inherited one.

If an own property gets deleted, then the inheritance re-activates:


const myObject = {

myProp: 'Value',

toString() {

return `[object MyObject]`;

}

};

// Own properties

myObject.toString(); // => '[object MyObject]'

myObject.myProp; // => 'Value'

delete myObject.toString;

delete myObject.myProp;

// Inherited property

myObject.toString(); // => '[object Object]'

// No inherited property

myObject.myProp; // => undefined


The first method invocation myObject.toString() uses the own property. Then delete myObject.toString deletes the own property.

The second invocation myObject.toString(), even having the own property toString deleted, uses the inherited toString property from the prototype object.

However, there's no myProp inherited from the prototype. When the own prop myProp is deleted from the object delete myObject.myProp, later the expression myObject.myProp evaluates to undefined.

5. Summary

A JavaScript object can have either own or inherited properties.

The own property means that the property is defined directly on the object. On the other side, the inherited property is the one inherited from the prototype object.

Knowing the difference between own and inherited properties is a big step in understanding the prototypal inheritance of JavaScript.

Dmitri Pavlutin

About Dmitri Pavlutin

Software developer and sometimes writer. My daily routine consists of (but not limited to) drinking coffee, coding, writing, overcoming boredom 😉, developing a gift boxes Shopify app, and blogging about Shopify. Living in the sunny Barcelona. 🇪🇸