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

Unusual marker appearing on every page utilizing ionic v1 and angularjs

For some unknown reason, a dot appears at the upper left side of each page in my webapp: https://i.stack.imgur.com/nN61t.png It seems to be an issue with the HTML code. When I run the snippet below, the dot is visible: <ion-view view-title="Send fe ...

What are the steps for implementing custom edit components in material-react-table?

I am currently using the official material-react-table documentation to implement a CRUD table. You can find more information at this link: . However, I encountered an issue while trying to utilize my own custom modal components for the "create new" featur ...

.load() not triggering for images that are not in the cache - jquery

In Safari and Opera, the callback function of .load doesn't wait for uncached images to be fully loaded. With cached images, it works perfectly fine. The code may seem a little complicated, but I'll do my best to simplify it... So, here is my J ...

Unable to precisely reach the very bottom of the scrollbar

When trying to move to the bottom of the scrollbar, I seem to reach a bit higher than the actual bottom. https://i.stack.imgur.com/Vt83t.png Here is my code: ws.onmessage = function (event) { var log = document.getElementById('log') ...

Connect a series of numerical input fields in Vue.js

One of the tasks I'm working on involves managing a table filled with rows of information. Users can choose multiple rows by checking checkboxes in each row, and I need to keep track of how many rows are selected by updating the totalSelected value. ...

Traverse an array containing nested objects using Javascript

I am facing difficulty printing out objects stored in an array. When I console log, this is the result: console.log(product.categories) https://i.stack.imgur.com/YVprQ.png How can I iterate through these nested objects to display them individually like t ...

The data list is failing to retain previous elements as new ones are incorporated

I have a list for uploads, and whenever I upload new data, the old data in the list gets removed. However, I want to display all the data together. How can I resolve this issue? const [fileList, setFileList] = useState<AddedFile[]>([]); const beg ...

A step-by-step guide on masking (proxying) a WebSocket port

Within my server-side rendering React app, I have set up a proxy for all HTTP calls to a different port. Take a look at the code snippet below for the HTTP proxy configuration. import proxy from "express-http-proxy"; const app = express(); const bodyParse ...

What is the best way to send a JSON Object containing option parameters in order to open a new window?

Have you noticed the interesting parameter list for the window.open() object? Is there a possibility to use window.open({options..}); instead? What are your thoughts on this matter? ...

Update the JavaScript and CSS files following an AJAX request with $.get

I am encountering an issue where my global CSS and JS files contain all the necessary definitions, but when I load new HTML blocks via AJAX $.get, these new elements do not receive the correct CSS/JS definitions. Is there a convenient way to refresh the ...

Error encountered while executing node server.js for Azure IoT Hub due to incorrect flags provided in the RegExp constructor

Currently, I am attempting to execute 'node server.js' in order to establish a connection between my Raspberry Pi device and Azure through the Azure IoT Hub. However, upon running the command 'node server.js', an error message is displa ...

Instructions on creating a number increment animation resembling Twitter's post engagement counter

I've been attempting to replicate the animation seen on Twitter's post like counter (the flipping numbers effect that happens when you like a post). Despite my best efforts, I can't seem to make it work. Here is what I have tried: $(fun ...

Tips for ensuring that a server waits until a database connection is successfully established using node.js, MongoDB, and Express

I have a server.js file and a database.js file In the server.js file, I have the following code: const express = require('express'); var db = require('./database'); const app = express(); . . some get/post methods app.listen(3000); . ...

Guide on storing images in a designated folder using CodeIgniter

My code is located in view/admin_view2.php <?php echo form_open_multipart('home_admin/createBerita'); ?> <div class="form-group" > <label class="control-label">upload foto</label> <inpu ...

Output PHP code within the HTML content using javascript's innerHTML functionality

I wrote a PHP function that increments by +1 every time it is executed. function count_likes(){ $collect=file_get_contents('like_counter.txt')+1; $count=file_put_contents("like_counter.txt", $collect); echo $collect; I also have a JavaScr ...

How come my counter is still at 0 even though I incremented it within the loop?

Within my HTML file, the code snippet below is present: <div id="userCount" class="number count-to" data-from="0" data-to="" data-speed="1000" data-fresh-interval="20"></div> In my Ja ...

Double request being sent by Ajax

Sample URL: Note: Please use the test sign in credentials: test/test for username/password. I am currently working on an AJAX request to fetch data from a database. The serverTime.php file appears to be functioning correctly as it is inserting and return ...

Keep the music playing by turning the page and using Amplitude.js to continue the song

I have implemented Amplitude.js to play dynamic songs using a server-side php script. My objective is to determine if a song is currently playing, and if so, before navigating away from the page, save the song's index and current position (in percenta ...

Error message: The function for the AJAX call is not defined

I'm currently working with jQuery's ajax function and encountering an error: 'getQty is not defined' Can you spot my mistake here? jQuery Code: function getQty() { var dataString = "itemId=" +$(".itemId").val(); $.ajax({ t ...

What sets apart window.location.href from this.router.url?

I'm curious about the various methods of obtaining the current URL in Angular. For instance: this.router.url My main question is: What advantages does using this.router.url offer over simply using window.location? Could someone kindly provide an exp ...