What is the functionality of __proto__ when an object is initialized using Object.create(null)?

Take a look at this javascript snippet:

var x = Object.create(null);
x.bar = 2;
var y = Object.create(x);
console.log(y.bar);  //outputs 2
console.log(y.__proto__);  //outputs undefined
y.__proto__ = null;
console.log(y.__proto__);  //outputs null
console.log(y.bar);  //outputs 2

How is it possible for object y to access the property "bar" of object x even after setting y.__proto__ to null? Is there an invisible connection that allows this property access?

I looked into various resources for insights on this matter, but I couldn't find a satisfactory explanation for this unique behavior in Javascript.

Answer №1

It appears that the issue lies in your usage of the outdated deprecated __proto__ property. This property acts as a getter/setter on Object.prototype, but since your objects do not inherit from it, initially, it is set to undefined, and assigning a value creates a standard property named __proto__.

To resolve this, you should utilize the appropriate methods like Object.getPrototypeOf/Object.setPrototypeOf. By making this adjustment, your code will function as intended:

var x = Object.create(null);
x.bar = 1;
var y = Object.create(x);
console.log(y.bar); // 1
console.log(Object.getPrototypeOf(y)); // {bar:1} - x
Object.setPrototypeOf(y, null);
console.log(Object.getPrototypeOf(y)); // null
console.log(y.bar); // undefined

Answer №2

According to the explanation provided by @Bergi, let's delve into what is actually happening with the __proto__ scenario:


var a = Object.create({});
var b = Object.create(a);
b.__proto__===a; //true
var c = Object.create(null);
var d = Object.create(c);
d.__proto__===c; //false..confusion

Object.hasOwnProperty.call(d,"__proto__"); //false as expected
Object.hasOwnProperty.call(b,"__proto__"); //false ?

Object.hasOwnProperty.call(Object,"__proto__"); //false
Object.hasOwnProperty.call(Object.prototype,"__proto__"); //true

This clearly indicates that __proto__ exists only within Object.prototype.


Object.getOwnPropertyDescriptor(Object.prototype,"__proto__")
//{enumerable: false, configurable: true, get: ƒ, set: ƒ}

The __proto__ essentially acts as a getter setter, returning an internal link to the object's parent, like so:


get __proto__(){return this.hidden_internal_link_to_parent;}

In the case of b.__proto__ - Since b does not have the __proto__ property, it traverses through the [[prototype]] chain to a, then to a's parent and finally to Object.prototype. The latter has __proto__ which returns the link of b's parent, which is a.

Now, in the case of d.__proto__ - The link from d to Object.prototype is broken (d --parent-->c and c--parent-->null). Hence, d.__proto__ is undefined. However, d does possess an internal link to

c</code, retrievable via <code>Object.getPrototypeOf(d)
.

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

HTML5 enables users to pick their preferred font style

In my JavaScript and HTML5 course, I am working on developing a website where users can choose the background color and decide between using SANS SERIF or SANS fonts. The background color selection feature is already functioning successfully -- var inputC ...

Gulp and Vinyl-fs not functioning properly when trying to save in the same folder as the source file due to issues with

After exploring a variety of solutions, I have yet to find success in modifying a file in place using Gulp.js with a globbing pattern. The specific issue I am facing can be found here. This is the code snippet I am currently working with: var fstrm = re ...

jQuery dynamic id selection

I'm facing a challenge with dynamically generated forms that have dynamically generated IDs and potentially classes. Although the forms are identical, they each have a unique ID at the end. How can I target and manipulate each set of inputs individua ...

Using scope in ng-style to manipulate a portion of a CSS property value in Angular

I've been attempting to add a border using ng-style, but I'm struggling to figure out how to concatenate the value from the scope variable. None of the methods below seem to be working for me: <div ng-style="{'border-top' :'1p ...

Receiving HTML from NodeJs instead of JSON

I am currently working on a project that involves developing an app and landing pages. While we are using NodeJs with Axios and VueJs for the app part, the landing pages are built using simple jQuery. I need to make API calls for the landing pages, but I a ...

A marker popup in React with Leaflet closes immediately upon clicking when using leaflet-pixi-overlay

Currently, I am developing a leaflet map using React and PixiOverlay for better performance while drawing markers. However, I have encountered an issue with handling popups while working on the code below: The Marker's click event triggers correctly ...

Is it possible to have the background scroll downward while keeping some content centered in place at all times?

Attempting to achieve the following effect in JavaScript, HTML, and Sass: When scrolling down the page, the layers (ground, sky, space, etc.) move downward The content (a rocket flying in the sky) stays centered on the screen and will move horizontally l ...

Browsing a Collection of Objects within an Array in JavaScript

After making an ajax request to load a JSON file and parsing it to store a reference to the object, I encountered issues while trying to loop through the object due to its structure. Below is a snippet of the JSON data that I am working with: { "marker ...

Updating to a newer version of jQuery causes issues with pop-out submenus

Looking for a way to create a menu with pop-out submenus? Here's an example using jQuery: <script type="text/javascript"> $(document).ready(function() { var hoverAttributes = { speed: 10, delay: 1 ...

The problem with the CSS Grid effect

Looking for assistance in creating a grid layout similar to the one on this website: Upon inspecting the page source, I found the following code snippet: http://jsfiddle.net/o45LLsxd/ <div ng-view="" class="ng-scope"><div class="biogrid ng-scope ...

Converting a string to a number, even if it contains non-numeric

Is there a built-in function that can directly convert a string containing non-numeric characters to a number in JavaScript, without the need for using str.substring() followed by parseInt()? For instance, how can I efficiently convert the string x1 to th ...

Is there a way to automatically refresh random data from the server to the web client without the need for manual browser refresh?

Looking to send random data from the server to the web client without reloading the browser? Well, I've got you covered. Using a combination of web framework express.js, template engine pug.js, socket.io, and jQuery, you can achieve this seamlessly. ...

Top Method for Incorporating Syntax Highlighting into Code Blocks - React Sanity Blog

I'm currently exploring the most effective method to incorporate syntax highlighting into my react sanity.io blog. Here's a look at the article component I've developed using react: import React, {useEffect, useState} from "react"; import ...

"Is there a way to adjust the range slider to display currency instead of

I stumbled upon this amazing slider on codepen. Can someone guide me on how to adjust it to display a range from €500 to €6000 while keeping the vibrant red background? I've attempted various solutions like: <input id = "range" type = "range ...

Using NodeJS to perform asynchronous tasks with setImmediate while also incorporating private class

Today marks my first time experimenting with setImmediate. I've come to realize that it may not be able to run private class methods. Can someone shed some light on this? Why is that the case? Not Functioning Properly When trying to use a private cl ...

Bootstrap is causing issues with unidentified div elements

I recently embarked on creating a slideshow using HTML, CSS, and jQuery. After completing the slideshow, I decided to add an interactive page beneath it. To streamline the layout process, I opted to utilize Bootstrap. However, upon loading Bootstrap, I en ...

The absence of req.body in the app reflects an undefined state

I'm encountering an issue with my app and I believe showing you my code is the best way to explain the problem: var Meetup = require('./models/meetup'); module.exports.create = function (req, res) { var meetup = new Meetup(req.body); c ...

Warning: Attempting to destructure the property 'name' from 'req.body', which is undefined, is causing a TypeError

Currently, I am diving into the world of MERN Stack web development and running into a unique issue. When using Postmate to input data from the body to the database, everything works smoothly when done from the server.js file. However, when attempting the ...

Adding elements to an array within a JSON object in Angular: What you need to know

Within my json object named "flowComponents," there is a string called "name" and an array of strings labeled "edition." As an example: { "_id": "553e87f3205465e83b46999b", "name": "FLOWCOMPONENT_CONTACTCOMBINATION_EDITION", "__v": 0, "edition ...

The function 'create' is not a recognized property within the 'Completions' type

Recently, I've been experimenting with ChatGPT and have just installed the latest version 4.8.0. My current project is built on NextJS. Prior to this, I successfully completed a project using v3.something last month, but I'm encountering diffic ...