Ways to safeguard function constructor arrays from unauthorized alterations using get methods in JavaScript

I am dealing with a coding challenge that involves managing state in JavaScript. Here is the code snippet I have been working on:

function State(){
  const SecretState = {
    name: 'bob'
  }
  this.getState = () => SecretState;
  this.setState = (name) => SecretState.name = name;
}
const m = new State()

m.setState('Smith')

m.getState().name = 'Alice'

console.log(m.getState().name)

My goal is to receive "Smith" as the output at the final console log call. However, I also need to restrict the ability to modify the state within the getState method.

Answer №1

One issue in JavaScript is that objects are copied using reference, so when getState is called, it returns a reference instead of an object.

To resolve this issue, you can update the code to:

this.getState = () => ({...SecretState});

This code creates a new object and passes its reference, ensuring that the SecretState object is only accessible using the setter method. However, keep in mind that this method may not work for deeply nested objects, as Object spread only works for the first level.

function State(){
  const SecretState = {
    name: 'bob'
  }
  this.getState = () => ({...SecretState});
  this.setState = (name) => SecretState.name = name;
}
const m = new State()

m.setState('Smith')

m.getState().name = 'Alice'

console.log(m.getState().name)

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

Error: Unable to access the 'map' property of an undefined object......Instructions on retrieving a single post

import React,{useEffect, useState} from 'react' //import {Link} from 'react-router-dom' import { FcLikePlaceholder, FcComments } from "react-icons/fc"; const SinglePost = () => { const [data,setdata] = useState([]) co ...

What is the method for linking to another page ID using an <a href> tag?

On one of my pages, I have a section that references another page's div id to trigger a click event for editing specific form fields. This is the profile page: <a href="<?php echo base_url('settings_pro/edit'); ?>" name="pull-righ ...

Error with JavaScript slideshow The slideshow using JavaScript seems to

I'm currently utilizing a script from the WOW Slider (free version) that looks like this: var slideIndex = 0; function showSlides() { var i; slides = document.getElementsByClassName("mySlides"); dots = document.getEle ...

"Unleash the Surprise: Three.js Cube Spinning to an Unexpected

I'm working with a Three.js Cube that has six distinct sides. I've created a random number generator that produces a number between 1-6. When a button is clicked, I want the cube to rotate to that specific side based on the generated number. Wh ...

The Bootstrap drop-down feature refuses to open

I seem to be having trouble with a basic issue. I used the standard template from the bootstrap website, but for some reason, when I click on the dropdown menu in the navbar, it's not opening. Can someone help me figure out what's going wrong? & ...

Is it possible to adjust the height of the apprequests dialog?

I attempted the following code snippet: FB.UIServer.Methods["apprequests"].size = {width:600,height:320}; The width successfully adjusts, however, the height is restricted to a fixed value. Appreciate any help! ...

order in which child objects are drawn

Encountering the following issue: I am attempting to create rings around Saturn, but they appear to be rendered in an incorrect order: https://i.sstatic.net/rVg3H.jpg The problem lies in how each planet is constructed. Each planet is a child of a differ ...

Loading all stores simultaneously in ExtJS

In my application.js file, I have defined the code snippet below. It includes a long list of stores and views that need to be loaded. The issue arises because these components are loaded asynchronously. This means that if a user clicks a button before a s ...

Issues with Adding Commas to Numerical Values

I've added a comma separator to display the total value that is being updated for roundNum: $.fn.digits = function(){ return this.each(function(){ $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?! ...

Determine the exact location of a click within an SVG element

This block of HTML includes SVG elements: <div class="container"> <div class="spacer"></div> <svg> <g id="polygonGroup" transform="translate(80, 50)"> <polygon points="-60,-10 -35,-30 -10,-10 -10,30 -60,30"&g ...

Easily validate the contenteditable attribute of <td> element

I am currently working on a table that displays data from a MYSQL database. Whenever a user makes changes to an element in the table, I want the database to be updated using AJAX. Below is my JavaScript code for sending data in an editable row. function s ...

Challenge with caching jQuery selectors

Whenever I include HTML tag IDs in my code, everything seems to work fine. However, once I cache them, the code no longer functions properly. What could be causing this issue? Take a look at my code snippet: var NewFormContainer=$("#NewUserFormContainer" ...

Difficulty in detecting variable modifications during testing - Angular2+

After successful login, I expect a certain variable to be updated with the appropriate value. However, during testing, all I see is 'undefined' returned. This variable does change when interacting with the app, showing an error message like &apo ...

Error in Node REPL: Trying to access property '0' of undefined after adding a property to Object.prototype

After adding the name property to Object.prototype and attempting to reference Object.prototype, an error is encountered: TypeError: Cannot read property '0' of undefined" Although I am able to access Object.prototype.name, it seems like the na ...

In Angular, there is a situation where two input fields are both referencing the same event.target

I am facing an issue where I have two input fields that are linked to the same event.target.value object, but I want them to be separate. <form class="flex-list" [formGroup]="calculation_Input" (input)="input($eve ...

Experimenting with mocha and Nightmare.js, utilizing traditional syntax and without the use of ES6 features

Here is a real-world example that I am using: How to Use Nightmare.js without ES6 Syntax and Yield However, when I include it in a Mocha test, it times out. Here's the code snippet: describe('Google', function() { it('should perform ...

What is the method for identifying modules that rely on a specific module?

Is it possible to view all dependencies modules of a specific module, similar to this: npm-remote-ls <module-name> But how can we see the modules that depend on a particular module? Any help would be appreciated. Thank you. ...

Pattern for money with two decimal points and a comma as the separator

I have currently implemented regex in the convertNumberToString property, where a comma appears every 3 digits entered. The convertStringToNumber property simply removes the comma to convert it back to a number type. Now, I want to update the regex for t ...

Ideas for displaying or hiding columns, organizing rows, and keeping headers fixed in a vast data table using jQuery

My data table is massive, filled with an abundance of information. Firstly, I am looking to implement show/hide columns functionality. However, as the number of columns exceeds 10-12, the performance significantly decreases. To address this issue, I have ...

The appearance of the pop-up mask is displayed at lightning speed

Check out the demo here Here is the HTML code: <div class="x"> </div> <input class="clickMe" type="button" value="ClickMe"></input> This is the JS code: $(".clickMe").click( function() { ...