Unlocking the Correct Way to Retrieve JavaScript Class Properties

As I was creating a class constructor to manage my database, I found myself questioning the behavior of JavaScript along the way.

To simplify things and understand the problem better, I stripped it down to its bare minimum. Here is the core of the issue:

name.js

class Name {
    constructor(){
        this.value = 'mo'
    }
    setName(){
        this.value = 'moom'
    }
}

export default new Name()

sayName.js

import name from './name'

const outsideName = name.value

function sayName(){
    const insideName = name.value
    console.log(insideName) // => moon
    console.log(outsideName) // => mo
}

export default sayName

index.js

import name from './name'
import sayName from './sayName'

name.setName()
sayName()

Initially, I expected to see the same result in the console (moon). But why are the console outputs showing different values (mo !=== moon)? I would greatly appreciate any insights on this matter.

Answer №1

  1. Begin by making a new instance of Name
  2. Copy the value of its name property (mo) to outsideName
  3. Invoke name.setName() to alter the value of its name property to moon.
  4. Display the updated value of its name property.
  5. Show the value of outsideName

ExternalName remains unchanged after step 2 because you don't modify it further.


I simplified the scenario to its bare essentials.

You have the potential to simplify it even more.

let object = { foo: 1 };
let value = object.foo;
object.foo = 2;
console.log( object.foo, value);

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

Swapping values in JSON by comparing specific keys: A guide

I have JSON data that contains a key called reportData with an array of values: {"reportData":[ ["1185","R","4t","G","06","L","GT","04309","2546","2015","CF FE","01H1","20","23840","FF20"], ["1186","R","5t","R","01","L","TP","00110","1854","2016" ...

Customizing the color scheme of specific components using Material UI inline styling

I am currently customizing my TextFields from Material-UI. My background is black and I want both the textField border and text to be white. Here's the relevant part of my code: render() { const styles = { width: { width: '90%& ...

Troubleshooting JSON Array Index Problems

I'm having trouble reaching index 3 in the array using the javascript options on my webpage. The final question "are you satisfied with your choice?" is not showing up for me. I'm not sure what I might be missing or doing incorrectly in this sit ...

A guide to testing window.pageYoffset in webdriverIO using chai assertions

When conducting a selenium test using WebDriverIO and Chai, I encountered the need to capture the position of window.pageYoffset. Unfortunately, I was unable to find a direct way to do this in WebDriverIO. My initial attempts involved: browser.scroll(0, 2 ...

constructing a nested container using XMLHttpRequest

I am working on creating a nested div-container structure using AJAX and adding the text "Hello World" to the inner container. The outer container serves as a holder for the inner container in this case. Below is the code I have written: index.html: ...

Using JQuery to cycle a class with a timer

My list has the following structure <div id="slider"> <ul> <li class='active'> a </li> <li> b </li> <li> c </li> <li> d </li> <li> e </li> </u ...

A function is unable to update a global variable

I have been working on a form that allows users to set the hour, with JavaScript validation in place to ensure there is input in the form. Initially, the global variable "userInputHours" is set to 0. Within the function "validation()", when the user meets ...

Tips for modifying an axios instance during response interception

Is there a way to automatically update an axios instance with the latest token received in a response, without making a second request? The new token can be included in any response after any request, and I want to make sure that the last received token ...

I am looking to transmit information to the controller using AJAX

ajax console.log(total);//10 console.log(number);//4 var form = { total:total, number:number } $.ajax({ url: 'items/cart/update', type: 'POST', data:form }); Spring MVC controller @ResponseBody @P ...

Tips for delaying the evaluation of an input field

I have a field for a product where the quantity depends on another product's quantity (must be between 70% and 100%). The issue is, it evaluates so quickly that if the main field is '100', I can't enter '75' in the other field ...

Picking out specific elements from a component that is rendered multiple times in a React application

One of the challenges I face involves a component called card, which is rendered multiple times with different data. Here's how it looks: { this.state.response.reminders.map((item,i=0) =>{ return <Card key={i++} reminder={item} deleteRem={th ...

Determine whether one class is a parent class of another class

I'm working with an array of classes (not objects) and I need to add new classes to the array only if a subclass is not already present. However, the current code is unable to achieve this since these are not initialized objects. import {A} from &apo ...

Is there a way to automatically clear the comments form upon clicking the submit button in Next.js 14?

I need some assistance with clearing the previous inputted comment in my comment form after the submit button is clicked. I want to make it easier for users by automatically clearing the input field for a new comment. Here is the code I have so far, any ...

In MongoDB, learn the process of efficiently updating nested objects in a dynamic manner

We have a variety of nested configurations stored in MongoDB. Initially, we store the following object in MongoDB: const value = { 'a': { 'b': 1 } } collection.insertOne({userId, value}) Now, I would like to modify the object in ...

What is the process of adding new fields to a model in TypeScript?

I have created a test.model.ts file: export interface ITransaction { description: string; transactionDate: string; isDebit: boolean; amount: number; debitAmount: string; creditAmount: string; } export class Transaction implements ...

Type Error: Issue encountered while resolving module specifier

Upon trying to import the d3.js library in a project that utilizes npm, I encountered the error message: TypeError: Error resolving module specifier: d3. This issue specifically occurred while using Firefox. index.html <!DOCTYPE html> <html lang ...

What is the process for securing a photo to a canvas?

I have included <input type='file' id="image"> in my HTML code. How can I display the uploaded image on my canvas using p5.js? What is the best way to add an event listener to this action and transfer the uploaded file onto the ca ...

Is there a distinction in invoking a service through reference or directly in Dependency Injection?

QUERY: Are there any discernible differences between the two instances of utilizing a factory service? Instance 1: angular.module('ramenBattleNetworkApp') .controller('MainCtrl', function ($scope, Helpers) { var testArray = [1 ...

Attempting to invoke setState on a Component before it has been mounted is not valid - tsx

I've searched through various threads regarding this issue, but none of them provided a solution that worked for me. Encountering the error: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a b ...

Tips for creating a function that utilizes a select option value

I'm struggling with a form that includes two select inputs. I want the second input to only be enabled if the first one has been selected. I attempted using an onclick event, but it didn't work out as expected. Can anyone provide assistance? (apo ...