Is the concept of inheritance limited to just parent-child relationships or does it extend to all children of a prototype as well?

Initially, I believed that objects only inherit from their parent to child, but the code I wrote reveals an unexpected inheritance among "siblings". This made me question why all the objects in my array testObj (which are children of myObj) share the same data. The code I wrote was purely for learning purposes with no particular goal in mind.

// Defining my prototype object
const myObj = {
    myArray: [],
    declaration: ""
}

// Creating an array of objects
let testObj = [];

// Populating my object
for (i=0; i < 4; i++) {
    testObj[i] = Object.create(myObj);
    testObj[i].myArray.push("content of array " + i);        
}

// Printing the data
testObj.forEach((eleA,idxA) => {
    console.log("\nobj number "+idxA);        
    eleA.myArray.forEach((eleB,idxB) => {
        console.log(eleB);
    });
});
Console Output:

obj number 0
content of array 0
content of array 1
content of array 2

obj number 1
content of array 0
content of array 1
content of array 2

obj number 2
content of array 0
content of array 1
content of array 2

https://jsfiddle.net/tkzw2fn8/

Answer №1

Imagine you have an object (A) with a property that contains an array.

By using Object.create, you can create new objects (AA, AB, AC) that inherit from A.

When you access the myArray property for each of AA, AB, AC and use push to modify it, they all point back to the same array in object A due to prototypal inheritance.

Essentially, prototypal inheritance does not duplicate the inherited values but rather shares them among different objects.


To sum up: Prototypal inheritance retains references instead of creating independent copies.

Answer №2

Alright, buckle up because this explanation is going to be a bit lengthy but bear with me. When you inherit an Array called "myArray" through the prototype chain in JavaScript, you're essentially getting a reference to that array. That's why any changes you make to it will reflect everywhere it's being accessed.

console.log(myObj.myArray);

Even if you try to access it like this, you'll see that it's the same as the other objects. Here's where things get tricky - when you try to modify the declaration property inside a for loop like this:

testObj[i].declaration="test"+i;

You'll notice a different behavior. This is because JavaScript uses something called "Shadowing" properties, which only applies to primitive types. So when you change an array, it changes everywhere due to being inherited by reference, whereas a primitive type like "declaration" does not.

In order to have a unique array for each object, you'll need to recreate that array only if it exists up the prototype chain, otherwise it will be inherited by reference and remain the same across all objects. This will effectively change the reference.

I hope this explanation helps clear up some of the confusion surrounding this topic.

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

Objects and strings cannot be inserted into a JavaScript array

For hours, I've been attempting to troubleshoot this code. Currently, it successfully finds the number of anchors, and I have an array that is of undetermined size. Within the for loop, it retrieves the anchor and extracts the .href. I've confirm ...

SVG images suddenly disappearing in Chrome following a javascript script execution

My webpage has a sticky footer, but I am experiencing issues with SVG files not displaying in Chrome when the javascript for color changing on hover is enabled. Interestingly, disabling the javascript allows the images to load properly in Chrome. I have t ...

Tips for altering Koa's HTTP status code for undeclared paths

If an undefined route is accessed on a Koa server, what is the best method to change the default HTTP status code and response body? Currently, Koa returns a 404 status and 'Not Found' text in the body. I intend to modify this to 501 (Not implem ...

Highlighting the Active Navigation Menu for the Current Page Using a Unified Header File

Is there a way to highlight the navigation menu for the current page I am visiting? header.php <div class="header-menu"> <div class="nav"> <ul> <a href="index.php"><li>Home</li> ...

Exploring Facebook Graph Data with Meteor 1.3

During my time using Meteor 1.2, I utilized the following code on my server to access user data and friends data: function Facebook(accessToken) { this.fb = Meteor.npmRequire('fbgraph'); this.accessToken = accessToken; this.fb.setAcc ...

What steps can I take to incorporate a user-controlled autoscroll feature into this Carousel?

I am in the process of creating a "slideshow" using text boxes that can be scrolled with arrow buttons. My goal is to have the slideshow automatically scroll only until the user interacts by clicking one of the arrow buttons. Below is the state logic re ...

The drop down menu in React does not show the selected value when a function is called in the onChange() event

I am currently developing a filter that retrieves data from serviceNow based on the user's selection in the drop down menu. In my onChange() function, I have a call to a filtering function (handleFilter()) which filters the data according to the value ...

Unable to convert the value "undefined" to an ObjectId (type string) in the "_id" path for the "Order" model

As someone who is new to Javascript and working on an e-commerce website, I am currently facing a challenge with displaying the order id on the return page. Each time I try to do so, I encounter an error message that reads Cast to ObjectId failed for val ...

Retrieve Gravatar image using JSON data

I am currently working on extracting data to show a user's Gravatar image. The JSON I have is as follows: . On line 34, there is 'uGava' which represents their gravatar URL. Ideally, it should be combined with / + uGava. Currently, I have ...

Select from a list to save

My goal is to create a feature where users can select a hotel name, number of days, guests, and peak time, the system will calculate them together and give a sum. Furthermore, I wish to store all user selections in the database, including the calculated to ...

A guide on accessing React hook state within a Highcharts event listener

Struggling to update state within an event listener using React hooks and attempting to add to the existing state: import React, { useState } from 'react'; import { render } from 'react-dom'; import HighchartsReact from 'highchart ...

The error message received states: "materialize-css Uncaught TypeError: Vel is not defined as

My current setup involves webpack as the bundler/loader, and I've successfully loaded materialize css (js/css). However, when attempting to use the toast feature, an error is thrown: Uncaught TypeError: Vel is not a function The library is being inc ...

Is it possible to have the Target='_blank' attribute open the link in a new window instead of a new tab?

Is there a way to achieve this? When using Firefox, the link opens in a new tab, which I prefer to avoid users having to adjust settings in their browsers. I am looking for a solution where a pop-up contact form appears whenever a user clicks on 'co ...

Can an AJAX upload progress bar be implemented in Internet Explorer without using Flash?

I've been searching for solutions to upload files without using flash, but all of them either require flash or lack a progress bar on IE (7-8). I couldn't find any mention of an "progress" event in the MSDN documentation for XMLHTTPRequest. Is i ...

What could be preventing my CSV file from being saved empty?

I am currently working on a function that processes the results of a web scraping operation I conducted on an online t-shirt store. Every t-shirt is represented as an object, featuring attributes such as title, price, imgUrl, URL, and time. These objects ...

Arrays in Vue Data

After creating an array and pushing data into it, the array turns into a proxy, preventing me from using JavaScript array functions on it. export default { name: 'Home', components: { PokeList, FilterType, SearchPokemon}, data() { r ...

Designing a unique shape geometry using THREE JS

I've been struggling to replicate an existing city in a 3D environment using THREE.js. I have coordinates for approximately 1000 buildings, each with a varying number of corners making it impossible to use standard cubeGeometry. I attempted to create ...

ViewContainerRef fails to render component on the DOM

@Component({ selector: 'my-cmp', template: ` <div #target></div> ` }) export class MyCmp { @ViewChild('target', {read: ViewContainerRef}) target : ViewContainerRef; render() { let component = createComponent(met ...

Displaying only the validation messages that are accurate according to the Vuetify rules

<v-text-field label='New Password' class="required" v-model='password' type='password' :rules="passwordRules" required> </v-text-field> passwordRules: [ value => !!value || 'Pl ...

Calculate the total of JSON objects while eliminating duplicates in an array

Below is an array of objects: const lineItems = [ { "lineNumber": "0", "item": "1496", "itemDesc": "wertyuiasdfghj", "qualityReceiptHold": "N", ...