instances of nested objects

I'm struggling with nested objects and prototyping. In the example below, I am creating 2 instances of object "o".

var o = function(){};

o.prototype = {
val : 1,
test : {
        val2 : 1
    }
};

var t1 = new o();
var t2 = new o();

t1.val = 5;
t2.val = 20;

t1.test.val2 = 5;
t2.test.val2 = 10;

console.log(t1.val) //5
console.log(t2.val) //20

console.log(t1.test.val2) //10
console.log(t2.test.val2) //10

I'm puzzled as to why t1.test.val2 === t2.test.val2, even though t1 and t2 are different variables. Shouldn't they be completely separate entities?

Any suggestions on how to modify the code so that all objects and variables remain distinct?

Answer №1

Creating a new object results in the prototype being duplicated, however, objects within the prototype are not deep-copied; rather, they are copied by reference. Therefore, every new instance of o will have a referenced copy to the same member objects of the prototype.

To avoid this, construct the test object within your constructor so that each instance has its own unique copy:

var o = function(){
    this.test = {
        val2 : 1
    }
};

o.prototype = {
    val : 1   // This is acceptable as primitive values are not copied by reference
};

Answer №2

The reason for this issue is because you are altering a property of a shared object (specifically, the prototype). Your code can be likened to the following:

var value = 1;
var obj = {
    value2: 1
};

var t1 = {
    value: value,
    obj: obj
};
var t2 = {
    value: value,
    obj: obj
};

t1.value = 5; // modifying property
t2.value = 20; // modifying property

t1.obj.value2 = 5; // changing property of shared object
t2.obj.value2 = 10; // changing property of shared object

To resolve this, avoid using the prototype, like so:

var newObj = function(){
    this.value = 1;
    this.obj = {
        value2: 1
    };
    // each instance now has its own 'obj' property, not shared
};

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

What is the process for invoking a page using a JavaScript function?

My index.php has a javascript code that calls a page in the following way: id = 5; var url = 'pages/pg/'+id+'/'; f.action = urlss.toLowerCase(); return true; The issue arises when I try to call the same page with a different ID, it do ...

Unable to retrieve state values or any methods that were declared from renderRow in React-Native

I am facing an issue with my listview. Whenever a user clicks on an item, I want something to happen using onPress (touchable highlight). I attempted to define functions and then call them in onPress, but it didn't work as expected. First, I defined ...

Need a place to keep your data safe while using nodejs?

I have taken on the task of developing a lastfm plugin for a chat bot that my friend created. One feature I want to include is the ability for users to register their hostmask/nick with their lastfm username (for example, using the command !reg lastfmuser ...

Implementation of the I18next library

I am currently integrating react-i18next into my application to implement a switch button for French and English languages. Unfortunately, I am facing some issues as the translation is not working properly. I suspect it's related to the JSON file reco ...

SimpleLightBox refuses to function

Having trouble getting SimpleLightBox to work properly? It seems like when you click on an image, it opens as a regular image on a blank page. I've added the JS and CSS files correctly (I double-checked in the source code) and included the HTML and JS ...

What is the fate of the code that comes after executing history. push in React?

My go-to for routing is typically the Redirect component. It's straightforward since you just need to return the Redirect component when needed. However, I'm a bit lost when it comes to using history objects. In my code base, after pushing a rout ...

What is the proper way to implement JQuery within a constructor function contained in a JavaScript namespace?

Yesterday I ran into a problem when asking about using JQuery inside a JavaScript constructor function within a namespace. There was a bug in my code that caused me to get the answer to the wrong question. var NS=NS||{}; NS.constructor=function() { t ...

What is the best way to showcase a JSON array in a tabular layout?

I have a JSON array structured like this: [ { id: "001", name: "apple", category: "fruit", color: "red" }, { id: "002", name: "melon", category: "fruit", color: "green" }, ...

Vuejs Todolist List App experiences unanticipated alteration in task prop

I own a store that includes state, mutation, getters, and more. Within the state, there is a list of tasks like the ones shown below. const state = { tasks:[{ title: "Wake up", completed: false }, { title: "Item 2&quo ...

Obtain the content of the text in the row before by pressing the button within the

After researching answers to similar questions, I have been unable to find a solution that works for my specific situation. I am facing an issue with retrieving the text value of a dynamically appended row with the class idRow. The challenge arises when t ...

Internal Server Error 500: Issue with Ajax/JavaScript

I have reviewed some previous posts, but unfortunately, they did not provide the help I need. When my program runs and I click on a button to trigger a JavaScript function, nothing happens - there is no response. In the Chrome debugger under the network ta ...

What is the proper way to utilize a date filter with ng-model in AngularJS?

I've been struggling with what seems to be a simple task - converting a date string to a date object and formatting it in Angular. Here's the issue: In my Angular app and controller, I have the following code: myApp.controller('myAppCtrl&a ...

Using the jqLite .html() method directly as a watch listener in AngularJS

I'm attempting to use the jqLite function element.html directly as a listener for a watcher: angular.module('testApp', []).directive('test', function () { return { restrict: 'A', link: function (scope, element, ...

React: Updating while in the middle of a state transition is not allowed. Render functions should only be a simple representation of props and state

I am looking to set an active NavLink "submenu key" in the React state so that the onClick() method of NavLink can check if any NavLinks inside Collapse are active, and if they are, then don't toggle isOpen for Collapse. 1. I want to prevent collapsin ...

The Protractor tool (node:9208) threw an UnhandledPromiseRejectionWarning due to an ElementNotVisibleError, indicating that the element is not interactable. Despite this

I am attempting to interact with an element using protractor but encountering the following error (node:9208) UnhandledPromiseRejectionWarning: ElementNotVisibleError: element not interactable (Session information: chrome=69.0.3497.92) (Driver informa ...

Display the current date in YYYY/MM/DD format using a single method in React and TypeScript

Is there a better way to retrieve YYYY/MM/DD data using just one method? I attempted the following: date = created_at // from API const sendDate = `${String((date.getMonth() + 1)).padStart(2, '0')}${String(date.getDate()).padStart(2, '0&apos ...

Is it possible to incorporate dynamic variables into the directives of a nested loop? Plus, thoughts on how to properly declare variables in a node.js environment

Question Explanation (Zamka): <----------------------------------------------------------------------------------------------------------> Input Example: 100 500 12 1st Line: represents the left bound (L) 2nd Line: represents the right bound ...

How about inputting some text into a field?

Below is the code snippet for your reference: <div class="col-xs-12 col-sm-9"> <input id="Shipping_FirstName" name="firstname" ng-model="userOrder.Shipping.FirstName" type="text" class="form-control nsg-form--input ng-pristine ng-untouc ...

Tips for persisting form values even after refreshing the page - a guide to setting form values that stay in place

When I submit a long form, an external JavaScript validation is triggered to check the input field validity. If all fields pass validation, a jQuery modal appears prompting the user to either register or log in. If the user chooses to register and complet ...

Node.js: Promise chain abruptly stops after reaching a predefined limit without causing any errors

Currently, I am attempting to perform a straightforward operation in nodejs using promises. My task involves working with an array that consists of objects. These objects contain query parameters for a URL that I need to access through a GET request. As th ...