JavaScript requires the use of an underscore _ in order to access properties

Recently, I've been working on a code to construct a nested/recursive object/array tree. Upon implementing getters/setters to the object, I noticed that I can only access properties in the root of the tree using the "_" prefix. This becomes apparent around line 89 of the code, near where the console.logs begin.

// In this code snippet, my goal is to establish a single "template" object definition that can be utilized to build a tree structure consisting of branches and leaves of the same object type.
// Additionally, functions have been created to retrieve/set values for any properties of any leaf by utilizing an array representing the leaf's position within the tree.

// Define Object Template for Branches/Leaves
class objTemplate {
    constructor(SpineName, Width, Height) {
        this.SpineName = SpineName;
        this.Width = Width;
        this.Height = Height;
        this.Area;
        this.Leaves = [];
    }

    get SpineName() {
        return this._SpineName;
    }

    set SpineName(value) {
        if (value.length === 0) {
            console.log("Sline Name Is Required.");
            return;
        }
        this._SpineName = value;
    }

    // More getter/setter methods...

}

// Function to Add Leaf Objects to Tree 
function pushLeaf(Position, Tree, NewLeaf) {
    Position.reduce((val, prop) => { return val.Leaves[prop]; }, Tree).Leaves.push(NewLeaf);
}

// Other utility functions...

// Initial Tree Creation
var objTree = Object.assign(Object.create(Object.getPrototypeOf(objTemplate)), new objTemplate("Root", 4, 5));

// Adding Leaf Objects to Root Branch
pushLeaf([], objTree, new objTemplate("Oreo", 3, 4));
pushLeaf([], objTree, new objTemplate("Jupiter", 7, 3));

// Additional nesting of objects...

console.log(`Root Object Spine Name: ${getValue([], objTree, "_SpineName")}`); // Use "_" prefix when accessing properties with getters/setters
// Further console logs...

After integrating getters/setters, the necessity of using the "_" prefix for property access became apparent. While I could continue this practice uniformly across all positions in the tree, I'm unsure of whether this is considered standard or if there's a better approach altogether. Any guidance on this matter would be greatly appreciated!

Answer №1

When creating objTree using Object.assign() and Object.create(), the prototype is not being copied correctly.

If you simply change it to:

var objTree = new objTemplate("Root", 4, 5);

it will function as intended. This method applies to all nested objects; there is no need to create the root object differently.

// My aim is to establish a singular "template" object definition for constructing a tree of branches/leaves based on this object.
// Additionally, functions are included to access/set values for any leaf's properties using an array indicating the leaf's position in the tree.

// Define Branch/Leaf Object Template
class objTemplate {
    constructor(SpineName, Width, Height) {
        this.SpineName = SpineName;
        this.Width = Width;
        this.Height = Height;
        this.Area;
        this.Leaves = [];
    }

    get SpineName() {
        return this._SpineName;
    }

    set SpineName(value) {
        if (value.length === 0) {
            console.log("Sline Name Is Required.");
            return;
        }
        this._SpineName = value;
    }

    get Width() {
        return this._Width;
    }

    set Width(value) {
        this._Width = value;
        this._Area = this._Width * this._Height;
    }

    get Height() {
        return this._Height;
    }

    set Height(value) {
        this._Height = value;
        this._Area = this._Width * this._Height;
    }

    get Area() {
        return this._Area;
    }

}

// Add Leaf Object To Tree 
function pushLeaf(Position, Tree, NewLeaf) {
    Position.reduce((val, prop) => { return val.Leaves[prop]; }, Tree).Leaves.push(NewLeaf);
}

// Get Value From Leaf Object 
function getValue(Position, Tree, Key) {
    return Position.reduce((val, prop) => { return val.Leaves[prop]; }, Tree)[Key];
}

// Set Leaf Object Value 
function setValue(Position, Tree, Key, value) {
    Position.reduce((val, prop) => { return val.Leaves[prop]; }, Tree)[Key] = value;
}

// Create Initial Tree
var objTree = new objTemplate("Root", 4, 5);

// Add Under Root Object
pushLeaf([], objTree, new objTemplate("Oreo", 3, 4));
pushLeaf([], objTree, new objTemplate("Jupiter", 7, 3));

// Add Under Root / 1st Object 
pushLeaf([0], objTree, new objTemplate("Moonman", 5, 2));
pushLeaf([0], objTree, new objTemplate("Slade", 4, 4));
pushLeaf([0], objTree, new objTemplate("Bubba", 4, 6));

// Add Under Root / 2nd Object
pushLeaf([0], objTree, new objTemplate("Chicken Butt", 9, 5));
pushLeaf([0], objTree, new objTemplate("Boss", 3, 5));

// Add Under Root / 1st Object / 3rd Object
pushLeaf([[0], [2]], objTree, new objTemplate("Buddy", 6, 4));
pushLeaf([[0], [2]], objTree, new objTemplate("Roe", 4, 8));

// Add Under Root / 1st Object / 3rd Object / 2nd Object
pushLeaf([[0], [2], [1]], objTree, new objTemplate("Little Man", 6, 4);


console.log(`Root Object Spine Name: ${getValue([], objTree, "SpineName")}`); // When using getters/setters, use "_" prefix for property names on root level
console.log(`Root Object / 1st Object Spine Name: ${getValue([0], objTree, "SpineName")}`);
console.log(`Root Object / 2nd Object Spine Name: ${getValue([1], objTree, "SpineName")}`);
console.log(`Root Object / 1st Object / 3rd object Spine Name: ${getValue([[0], [2]], objTree, "SpineName")}`);
console.log("");

console.log(`Root Object / 1st Object / 3rd object / 2nd Object Width: ${getValue([[0], [2], [1]], objTree, "Width")}`);
console.log(`Root Object / 1st Object / 3rd object / 2nd Object Height: ${getValue([[0], [2], [1]], objTree, "Height")}`);
console.log(`Root Object / 1st Object / 3rd object / 2nd Object Area: ${getValue([[0], [2], [1]], objTree, "Area")}`);
console.log("");

console.log('Change Root Object / 1st Object / 3rd object / 2nd Object Width:');
setValue([[0], [2], [1]], objTree, "Width", 8);
console.log(`Root Object / 1st Object / 3rd object / 2nd Object Width: ${getValue([[0], [2], [1]], objTree, "Width")}`);
console.log(`Root Object / 1st Object / 3rd object / 2nd Object Height: ${getValue([[0], [2], [1]], objTree, "Height")}`);
console.log(`Root Object / 1st Object / 3rd object / 2nd Object Area: ${getValue([[0], [2], [1]], objTree, "Area")}`);

//console.log(JSON.stringify(objTree));

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

processes that are repeatedly called

<li class="cart_item clearfix" v-for="(product, index) in products" :key="index"> <div class="cart_item_text"><button type="button" class="btn btn-success" name=&q ...

Leveraging the power of LocalStorage in Ionic 2

Trying to collect data from two text fields and store it using LocalStorage has proven tricky. Below is the code I have set up, but unfortunately it's not functioning as expected. Can you provide guidance on how to resolve this issue? In page1.html ...

Challenges in the Knockout Framework Due to Synchronization Issues

Recently, I've encountered a slight problem with race conditions in my code. Utilizing Knockout.Js to collect information for user display has been the cause. The issue arises when a dropdown needs to be created before a value can be selected. Typica ...

The error message "Error: 'x' is not a defined function or its output is not iterable"

While experimenting, I accidentally discovered that the following code snippet causes an error in V8 (Chrome, Node.js, etc): for (let val of Symbol()) { /*...*/ } TypeError: Symbol is not a function or its return value is not iterable I also found out ...

Creating a Unique Carousel Design with Ant Design

https://i.sstatic.net/HobMm.jpg Steps to personalize the ant design carousel with these unique features: Use Bullets instead of Boxes Modify Bullet Color Place Bullets outside the image container Sandbox Link https://codesandbox.io/s/trusting-dream-zzjr ...

Show the month together with its corresponding year

Here is a representation of an array structure: 1 => array:7 [▼ "id" => "4" "order_code" => "BS-ORD-000000004" "order_type" => "Mixed - Subscription" "subscription_months" => "4" "subscription_start_month" => Carbon {#714 ▼ ...

Pop Ups in PHP: A Guide to Retrieving Variables

I'm a beginner in PHP and I have two files named file_upload.php and test1.php. On file_upload.php, there is a button: <input type="button" value="Link More Opinion" onclick="popUp('test1.php');" /> The JavaScript for that button: & ...

Could one harness the power of SO's script for adding color to code within questions?

Similar Question: Syntax highlighting code with Javascript I've observed that Stack Overflow utilizes a script to apply color coding to any code shared in questions and answers, making it resemble how it would appear in an IDE. Is this script pub ...

The functionality of the jQuery .on() method is not compatible with appending newly created DOM elements

While the jQuery .on() method is effective for handling 'click' events, it does not work with 'load' events. I am trying to add a class to a new DOM element after an AJAX load. Unfortunately, I am unable to edit the $('.nav a&apos ...

What is the best way to send the value from a textbox to this script?

My challenge is with this particular textbox: <input type="text" autocomplete="off" required="required" id="bar" name="bar" class="form-control" placeholder="Barcode"> Also, there's a button in the mix: <button type="button" style="float:r ...

Tips for implementing two Secondary Actions in React Material UI, with one positioned on the left corner and the other on the right, while ensuring that the behavior of the

Is there a way to display two secondary actions on either end of a list item without triggering additional onclick events? The placement can be adjusted by overriding the CSS properties right and left. https://i.stack.imgur.com/rhr7N.gif The issue arises ...

Using arrays as properties in literal objects

Attempting to articulate the issue is somewhat challenging, so please refer to the code snippet below. var test = { my_array: [], my_var: '' } var a = Object.create(test); var b = Object.create(test); a.my_array.push('aaa'); b.m ...

What is the reason for me encountering an error message stating "Access-Control-Allow-Origin" does not allow this origin?

I encountered the following issue: Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin when using the code snippet below: var http = new getXMLHttpRequestObject(); var url = "http://gdata.youtube.com/action/GetUploadToken"; var se ...

Experiencing difficulty importing .pem files into Express

Referred to by this previous inquiry which went unanswered: I've stumbled upon something peculiar. Despite my efforts, I am still unable to import my certificate. Every time I attempt to run my Node/express application, it crashes with the same error ...

Determine the worth of various object attributes and delete them from the list

Currently, my dataset is structured like this: { roof: 'black', door: 'white', windows: 8 }, { roof: 'red', door: 'green', windows: 2 }, { roof: 'black', door: 'green', windows: ...

Tips for sending every individual string object within an array as post data via ajax

I have a scenario where I am dealing with dynamically generated text boxes. Each value from these text boxes needs to be stored in a JSON array when submitted. The approach I took was to push all the values into an array and upon submission, these values a ...

Updating the model of a Vuejs single file component (.vue) within the <script> tag

Discovering the world of vuejs, I set out to create a basic single file component for testing purposes. This component's main task is to showcase a boolean and a button that toggles the boolean value. It also listens for a "customEvent" which trigger ...

JavaScript and PHP open-source libraries for enabling voice chat functionality

Seeking assistance on incorporating voice-chat functionality into my website through PHP and JavaScript. Are there any open-source libraries available for this purpose? I am willing to utilize Flash if necessary, but limited to using only Flash, JavaScri ...

Adding information to a JSON file using JavaScript: A step-by-step guide

Struggling to develop a basic Discord.js bot, I've hit a roadblock when it comes to incorporating user input into an array stored in a json file. My goal is to maintain a single json file to hold data that the bot can utilize, including a collection ...

Go through each .md document, transform them into HTML format, and dispatch them

I am using fs to read files in .md format and transform them into HTML files. Here is the code snippet I have written: fs = require('fs'); fs.readFile(__dirname + '/posts/react-v16.13.0.md', 'utf8', function (err, data) { i ...