Exploring the Difference Between __proto__ and __proto__ Accessor in MDN Documentation

According to the information provided by mdn in their documentation on JavaScript's Inheritance and the prototype chain, it is stated

All objects inherit the Object.prototype.__proto__ setter, which can be used to set the [[Prototype]] of an existing object (if the __proto__ key is not overridden on the object).

However, they also mention that

Object.prototype.__proto__ accessors are non-standard and deprecated. It is recommended to use Object.setPrototypeOf instead.

They provide an example as well:

const obj = {};
// THIS IS NOT ADVISED: for demonstration purposes only.
obj.__proto__ = { barProp: 'bar val' };
obj.__proto__.__proto__ = { fooProp: 'foo val' };
console.log(obj.fooProp);
console.log(obj.barProp);

The confusing part comes when they introduce this initial example:

const o = {
  a: 1,
  b: 2,
  // __proto__ sets the [[Prototype]]. It's specified here
  // as another object literal.
  __proto__: {
    b: 3,
    c: 4,
  },
};

By stating,

The syntax { __proto__: ... } is distinct from the obj.__proto__ accessor: the former being standard and not deprecated.

What sets apart { __proto__: ...} from obj.__proto__? As both are object properties, it is unclear what exactly distinguishes them in this context.

Answer №1

The design of the syntax dictates the approach. (Check out this and this for more information.) Deprecated is the act of assigning to the __proto__ of an existing object, but defining a __proto__ during object creation is acceptable.

An object literal can include it for starters, but altering it for an already-existing object is not advisable due to performance concerns as highlighted by MDN:

Note: Modifying an object's prototype with modern JavaScript engines may lead to slow property access optimizations in all browsers. When inheritance is changed, there could be widespread impacts that go beyond the Object.setPrototypeOf(...) call. More insights on optimizing prototypes can be found in JavaScript engine basics.

Engine developers are responsible for efficiently implementing this feature since it is part of the language. Until addressed, avoid modifying the [[Prototype]] if performance is a concern and opt for creating a new object with the desired [[Prototype]] using Object.create().

Typically, well-structured code should not necessitate altering an existing object's internal prototype dynamically. On the other hand, specifying an internal prototype upon initial object creation is standard practice.

(For adjusting an object’s internal prototype, methods like setPrototypeOf are available but discouraged, likewise with setting the object's __proto__, which is deprecated along with being advised against.)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Java persistence with AJAX technology

Being a beginner in server side development, I am currently working on creating a database application for my company that will store links to all our marketing videos. Each entry consists of a URL (link to video), description, industry, and more. So far, ...

Revise the form used to edit data stored in Vuex and accessed through computed properties

My form component is used for client registration and editing purposes. Upon creation of the form component, I check if there is an ID in the URL to determine which type of form to display. If no ID is present (indicating a new client registration), all fi ...

Sending multiple form fields using Ajax and the form ID to make a single submit call to the specified URL

<form id="adultval" class=""> <input id="txtFirstName" type="text" name="First Name" placeholder="First Name" class="form-control" minlength="2" required> <input id="txtLastName" type="text" name="Last Name" placeholder="Last Name" ...

What is the purpose of using the variable "header_row || 1" in App Script?

Recently, I stumbled upon a spreadsheet that contains app script for gathering keys of data requested through doGet. In the code, there is a line that reads like this: var headRow = e.parameter.header_row || 1; What exactly does this line mean? I searc ...

Is AngularJS the right choice for developing this application?

Recently, I've come to the realization that I want to dive into the world of AngularJS framework after working with jQuery for several years. I have a vision of developing an application that allows users to easily modify webpage DOM using a browser- ...

Ways to access the specified variable in JavaScript

How can I get to the header of a variable? For example, in the Redux Framework WordPress plugin, there is a variable [redux.args.opt_name]. How do I find the define line for this variable? Another Question: What does the use of two single quotes in the &a ...

Seeking the Bluebird promise method "any" within a sequence

One of my requirements involves running Promise.any in series. Since Promise.any is not available (correct me if I'm wrong), I created a function to execute promises sequentially using Pomise.mapSeries and resolve at the first satisfied test. The pr ...

Tips for transferring a variable from a hyperlink to a Flask application

Here is a snippet of my Python Flask code: @app.route('/ques/<string:idd>',methods=['GET', 'POST']) def ques(idd): print(id) And here is the accompanying Javascript code: var counts = {{ test|tojson }}; var text = ...

Is the return type for EvaluateJavaScript restricted to only String values?

One of the challenges I faced was creating a common function in Kotlin that could invoke a JavaScript function based on the command provided. fun evaluateJsFromNative(command: String, webView: WebView, function: (value : String) -> Unit ) ...

Delivering information to personalized components using React Bootstrap

I am working with a custom styled checkbox that is part of a mapped data array. {nfcArray && nfcArray.map((item, key) => { return ( <tr class="hover"> <td className="cell_style pl-3 pl-lg-5"> ...

Tips for preventing nested subscriptions from exceeding two levels

I have four subscriptions that depend on each other. While there are numerous suggestions on avoiding nested subscriptions, they often don't address more than two levels of nesting. How can I prevent so many nested subscriptions? This is the code fo ...

Ways to store the output of a <script src> tag into a variable

How can I retrieve the output of a file in JavaScript? I am looking to achieve: var list = <script src="src/users.json"></script> Is it feasible to accomplish this using JavaScript? ...

How to play audio with a source path that includes the special character "%" in JavaScript

Having an issue with playing an audio file that has '%' in its name. I've tried using the tag <audio src="test%320.mp3" controls></audio>, but it seems like the file is not being found when I try to play it. Can anyone ...

[entity: undefined prototype] { type: 'clip', info: 'Watch my latest video!!' } using nodejs - multer

import routes from "./routes"; import multer from "multer"; const multerVideo = multer({ dest: "videos/" }); export const localsMiddleware = (req, res, next) => { res.locals.siteName = "Webtube"; res.locals.routes = routes; res.locals.user = { isA ...

Having trouble seeing the filtered results in the React Redux search filter?

I have implemented a search filter using react redux, but I am encountering an issue. When I type in text in the search field, the list of projects does not change according to the value I input into the search field. This should ideally filter the project ...

Tips for handling numerous observables in Angular 7

I am working on an Angular 7 application that deals with a total of 20 sensor data. My goal is to receive data from a selected sensor every 5 seconds using observables. For example: var sensorId = ""; // dynamically chosen from the web interface var senso ...

Troubleshooting ng-if Error in AngularJS

I encountered an issue while trying to construct a conditional table, and received the following error message: TypeError: Cannot read property 'mData' of undefined This is the code I am using: ... <td ng-if="isNaN(element.exec.end)">{ ...

Issue with Next.js's notFound() function not properly setting the 404 HTTP Header

Our decision to use Nextjs was primarily driven by the need for SSR and SEO optimization. We rely on an external REST API to fetch data on the front end, but we face challenges when trying to pre-render certain pages and display a proper 404 Not Found head ...

Toggle Checkbox Group for Both Multiple and Single Selection Options

Need help with a function to enable only one checkbox for single selection or multiple checkboxes for multiple selection. Use MultipleCheckbox(0) for single selection or MultipleCheckbox(1) for multiple selection. function MultipleCheckbox(elem){ i ...

Create a new tab that is active and use ng-repeat in the uib-tab directive

I've been trying to solve this problem for a while now. I came across a similar post, but it was left unanswered. So, I decided to create my own post with a Plunkr example. The issue I'm facing is that upon loading, the ui-tab always defaults to ...