Child object referencing in JavaScript

As I delved into testing Javascript, a curiosity arose regarding the interaction between child and parent objects. Would the parent object dynamically update to reflect changes in the child object's value, or would it remain static at the initial state of the child upon instantiation?

Within my miniature module coords.js

var NS = NS || {};

NS.Coords = function(){

    var __parentArray = {};
    var __childArray = {};

    addToParent = function(){
        __childArray['value'] = "Initial";
        __parentArray['child'] = __childArray;
    },

    showParent = function(){
        console.log("Parent: ",__parentArray);
        console.log("Child within parent: ",__parentArray['child']);
    },

    changeChild = function(){
        __childArray['value'] = "Changed";
    },

    showChild = function(){
        console.log("Child: ",__childArray]);
    };

    return {
        addToParent: addToParent,
        showParent: showParent,
        changeChild: changeChild,
        showChild: showChild
    };

}();

Continuing in main.js

var NS = NS || {};

// @codekit-prepend "Coords.js"

console.log("=============================");
console.log("Startpoint point");
console.log("=============================");
var coords = NS.Coords;
coords.addToParent();
coords.showChild();
coords.showParent();

console.log("=============================");
console.log("Changed child value");
console.log("=============================");
coords.changeChild();
coords.showChild();
coords.showParent();

Upon running this code, the console displays an interesting observation. The child object correctly displays both the "Initial" and "Changed" values. However, the parent object consistently shows the "Changed" value for the child object, even prior to invoking the 'changeChild()' function. This unexpected behavior raises questions - am I overlooking a simple concept, or is there a deeper misunderstanding at play?

Answer №1

One issue could be that you are using GOOGLE CHROME. While this isn't a major problem, keep in mind that any property changes are reflected in the console AUTOMATICALLY. Quite magical, right?

To ensure your script is functioning correctly, try changing

console.log("Child within parent: ",__parentArray['child']);
to
console.log("Child within parent: ",__parentArray['child']['value']);
.

You can access the fiddle here: http://jsfiddle.net/M4Cd8/

Answer №2

After addressing the syntax errors in your code, the behavior you described should no longer be an issue. Some browsers' consoles have a feature that displays an updated reference to objects as they change. To observe the value string instead of the entire object:

console.log("Child within parent: ",__parentArray['child'].value);
console.log("Child: ",__childArray.value);

http://jsfiddle.net/pNtJJ/

To clarify, if you modify an object that another object references, the change will be reflected regardless of how you monitor it, because a reference is essentially a connection between two objects.

On a side note, even though your variables contain the word "array," they are not actually arrays but objects. Arrays are typically denoted by square brackets like [1, 2, 3, 4] and contain only values, not key-value pairs.

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

Update the nodes in a directed graph with fresh data

For the past few days, I've been facing a persistent issue that I just can't seem to find a solution for when it comes to updating nodes properly. Using three.js to render the graph adds an extra layer of complexity, as the information available ...

displaying outcomes as 'Indefinite' rather than the anticipated result in the input field

I need to automatically populate values into 4 text fields based on the input value entered by the user. When the user exits the input field, a function called getcredentials() is triggered. This function, in turn, executes Python code that retrieves the r ...

What is the best way to check if a specific value is present in a JavaScript Array using a Function?

When a person uses an input field to type in a value, I have created the variable 'Ben' for that purpose. My goal is for a function to loop through the nameArray and return either true or false. Unfortunately, the script I've written isn& ...

Canvas displaying inaccurately (unsteady)

While working on a simple HTML5/javascript game, I encountered an unusual issue with the canvas drawings - they seem to be unstable. I have a map that needs to be drawn in a specific way: The background consists of 2 layers: the ocean and the islands. Th ...

Looking for advice on how to design a custom JavaScript widget?

I am currently working on a web application and I am in the process of developing a feedback form widget that users can easily embed on their websites. The data submitted through this widget will be securely stored within my web application. One important ...

Each loop iteration results in the array being randomly ordered

My goal is to store multiple objects in an array and then render them out in a specific order. This is my process: app.js var allOdds = []; var count = 0; // ===================================== /* Database Configuration and Error Handling */ // ====== ...

Angular file upload component with customizable file size limits

I'm currently developing an upload file feature that will transmit the file via nodejs. However, I am encountering an issue related to file size. Whenever the file exceeds a few kilobytes, I encounter the following error: Error: request entity too la ...

Discover the technique of accessing HTML/CSS toggle switch value in Golang

I am attempting to incorporate a toggle switch into my webpage. I followed this specific tutorial for guidance: w3schools.com Currently, I have set up my HTML file with a button and the toggle switch. Additionally, I configured my web server in Go to lis ...

Turn off scrolling for the body content without removing the scrollbar visibility

Whenever I click a thumbnail, a div overlay box appears on top: .view-overlay { display:none; position:fixed; top:0; left:0; right:0; bottom:0; overflow-y:scroll; background-color:rgba(0,0,0,0.7); z-index:999; } Some browsers with non-f ...

What causes variations in running identical code between the Node environment and the Chrome console?

let myName = "World"; function functionA() { let myName = "FunctionA"; return function() { console.log(this.myName); } } functionA()(); Executing the code above in my terminal with node results in undefined, while running it in Chrom ...

Problem with animated scrolling in Jquery

Currently, I am working on a function that aims to smoothly scroll the web to a specific div each time a user scrolls "into" a container div. You can get a better idea of what I mean by looking at my JSFiddle. Everything works perfectly when the user scro ...

Trouble with refreshing button after resolving routes in Angular UI Router

My Angular UI router is giving me trouble. When I navigate to the state below, everything works smoothly. However, if I refresh the page, the resolve function retrieves the data, injects it into the controller, but the view does not load. Essentially, th ...

Receiving user input in ajax

I have an operational PHP page with an AJAX call. I am currently attempting to obtain user input through a text entry field and then pass it through _GET into AJAX. Here is the code snippet: <body onload="test()"> <script> function test () { v ...

Determine if the given text matches the name of the individual associated with a specific identification number

Struggling to create a validation system for two sets of fields. There are 6 inputs in total, with 3 designated for entering a name and the other 3 for an ID number. The validation rule is that if an input with name="RE_SignedByID" contains a value, then c ...

Unable to locate the internal/fs module, current solutions are proving ineffective

Every time I try to run my project, I encounter the same issue despite downgrading my node version to 8.4.0 (npm version 5.3.0). I have tried various solutions such as removing the node_modules, running npm cache clean --force, and then npm install, but no ...

Issues have been encountered with the functionality of $rootScope

I am currently struggling with a code snippet in my loginCtrl.js file where I can't seem to get $rootScope to store the value of vm.userEmail. app.controller('LoginCtrl', function($timeout, $q, $log, $rootScope /*$auth*/, $location, $mdTo ...

Perform a JSON POST request from an HTML script to a Node.JS application hosted on a different domain

In an attempt to send string data via a post json request using JavaScript within an .erb.html file, I am facing the challenge of sending it to a node.js app on another domain that uses express to handle incoming requests. After researching online, I have ...

Bootstrap Modal closing problem

While working on a bootstrap modal, I encountered an issue where the modal contains two buttons - one for printing the content and another for closing the modal. Here is the code snippet for the modal in my aspx page: <div class="modal fade" id="myMod ...

JavaScript-Based Header Features Similar to Excel

Currently, I am in the process of developing a function that generates a sequence of strings similar to Excel headers. For those who may not be familiar with Excel, the sequence goes like this: A,B,...,Z,AA,...,AZ,BA,...,ZZ,AAA,...,etc. Here is the code ...

A JavaScript variable... cannot access

Can anybody explain to me the reason behind this reference not functioning properly? let linkId = $(this).attr("data-id"); //retrieve the id data when a tag is clicked $(".wrapper").find("section[id=linkId]").css({"background-color": "red"}); ...