Using Typescript/JSX to assign a class instance by reference

Looking to access an object's property by reference? See the code snippet below;

class Point{
  x:number;
  y:number;
  constructor(x,y)
  {
    this.x=x;
    this.y=y;
  }
}

const a = { first: new Point(8,9), second: new Point(10,12) };
let someBool = true;

function modifyProperty(a) {
  let c = someBool? a.first: a.second;

  let newPoint = new Point(0,0);
  c = newPoint;         // Doesn't work

  someBool = !someBool;
}

modifyProperty(a);
console.log(a.first);

In this scenario, alternating between modifying 'a' properties when calling modifyProperty() doesn't quite work as expected.

One possible solution involves making the properties in 'a' objects themselves. Essentially like so:

 const a = { first: {value: new Point(8,9)}, second: {value: new Point(10,12)} };

This allows you to assign a new value to 'c' using c.value = newPoint. However, this workaround is not ideal given that it would need to be done for each property within an object.

Is there a better way to achieve pass-by-reference for accessing these properties? While JavaScript only supports this for objects and arrays, what about instances of classes?

Noting how Babel treats classes as functions in standard Javascript conversion, could utilizing their object callable nature provide a potential solution?

Answer №1

Nevertheless, whenever I allocate 'c' to either 'a.first' or 'a.second', it simply passes by value

Absolutely, when you assign a value in JavaScript or TypeScript, it always changes the value on the left side of the equal sign (=). Unfortunately, there is no way to change this behavior.

An alternative approach is to utilize the property name along with the object to which the property belongs rather than using a reference:

type Pair<T> = { first: T, second: T }

function modifyProperty(a: Pair<Point>) {
    let c: keyof Pair<Point> = someBool? 'first' : 'second'; 
    // The keyof Pair<Point> type annotation ensures that only property names from Pair can be assigned to c  

    let newPoint = new Point(0,0);
    a[c] = newPoint;         

    someBool = !someBool;
}

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

The $.parseJSON function accurately retrieves valid items but also presents an endless stream of undefined

Currently, I am in the process of developing a Flask application that fetches teams from a football league. The teams_list method returns the result of an AJAX request. While the output is correct, it seems to trigger an infinite loop that significantly sl ...

Compare the selected values of radio buttons with an array and find matches

I have multiple radio button groups, where each selection in a group corresponds to predefined values in an array. For example, selecting option 1 in Group 1 will increment values A and B by 1, while selecting option 2 will increment B, C, and D. The goal ...

Alert: Refs cannot be assigned to function components. Any attempt to access this ref will result in failure. Have you considered using React.forwardRef()? displayed in the @Mui Component

Is anyone familiar with this particular component? <Controller control={control} {...register("DOB", {})} render={({ field }) => ( <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePicker ...

Styling in Svelte/TS does not change when applied through a foreach loop

I've been experimenting with creating a unique "bubble" effect on one of my websites, but I'm facing difficulty changing the styling in a foreach loop. Despite no errors showing up in the console, I'm at a loss as to how to effectively debu ...

Locally hosted website failing to transfer login details to external domain

Having trouble with an ajax call that is supposed to retrieve data from a web page, but instead returns a jQuery parse Error. Even though I can access the page directly, the ajax call doesn't seem to be working and storing the result properly. Below ...

Is it possible to trigger the Facebook Pixel Code using the <noscript> element through programming?

Is there a way to programmatically call the Facebook Pixel Code using noscript? I am facing an issue with the Facebook Pixel Helper extension breaking when the script and noscript code are separated. Can a function be wrapped around the code or built in th ...

What is the process of importing a file as text into vite.config.js?

Within my project directory, there is a simple SCSS file that I need to access its content during the compilation process in order to transform it in vite.config.js. However, I am unsure of how to retrieve its content. I have successfully obtained the cont ...

Activating JavaScript in the browser only when a button is manually clicked, not by default

As I work on my website, which is currently being constructed, I rely heavily on JavaScript. However, a concern of mine is the potential for failure if a user has JavaScript disabled on their client side system. I understand that it is not possible to pro ...

Enhanced SSL connectivity features in Meteor version 1.8.1

My development server is running on localhost (Windows 10 Pro x64 build 1903) and will eventually be moved to the production environment (Galaxy). To enable authentication through Facebook or Google, HTTPS is required. I configured Nourharidy Meteor SSL on ...

Why are my variables resetting in Angular after ngAfterViewInit?

There seems to be an issue with my variables resetting after successfully using them in ngAfterViewInit(). I have a few @ViewChild and regular variables that are utilized or set in ngAfterViewInit. However, when certain events that I added post-initializa ...

Creating dynamic charts in Javascript using Firebase

My dad recently asked me to enhance our motor home by integrating an Arduino with Firebase to monitor the water and propane tanks. He's hoping to be able to check tank levels from his phone so he can see when they need refilling. I've successful ...

Angular asynchronous operations are failing to complete within the specified time frame

Observations suggest that Angular's async from @angular/core/testing is not properly resolving timeouts in tests when a beforeEach contains async as well. Sadly, the bug cannot be replicated on Plunkr or JSFiddle platforms. To reproduce this issue ea ...

Is there a way to determine if a website is utilizing javascript?

Currently, I am in the process of developing a web scraping tool using beautifulsoup. Some of the websites I am targeting contain JavaScript elements that prevent me from using urllib3 efficiently. As a workaround, I have incorporated selenium into my sc ...

Creating a hash map for an iteration through a jQuery collection

Using the jQuery .each function, I traverse through various div elements. By using console.log, the following output is obtained: 0.24 240, 0.1 100, 0.24 240, 0.24 240, The first number on each line represents a factor and the last number is the res ...

utilizing the JavaScript SDK to send alerts to a user's friends on Facebook

I am attempting to send a notification to a user's friend using the JS SDK on a Facebook canvas app, but I'm encountering this error in the console: POST https://graph.facebook.com/16542203957691/notifications? 400 (OK) jquery.min.js:140 c.exten ...

Deactivate the button upon click using alternative methods besides the disable attribute

I am trying to implement functionality with 3 buttons: 'click me', 'disable', and 'enable'. When the 'click me' button is clicked, it triggers an alert. However, when the 'disable' button is clicked, it sho ...

Send a file from a form using Gatsby to getform.io using the axios library

I am facing an issue with my getform.io form where the file is not getting uploaded properly. The file appears as [] and the files tab remains empty. Upon checking the network tab, I noticed that my request payload includes {email: "[email protec ...

Concealing the text input cursor (caret) from peeking through overlaid elements on Internet Explorer

Currently, I am facing an issue with a form that includes a unique widget. This particular widget automatically populates a text input when it is in focus. The problem arises when the widget appears above the text input as intended. In Internet Explorer ...

Navigating through PWAs and implementing deep linking in both single page applications (SPAs) and multi-page applications

QUESTION: How can navigation, history, and deep-linking be managed in a PWA without relying on a heavy JS Framework? Tasked with transitioning an existing shopping website from Angular 1 SPA to a Multi Page App (MPA) PWA, I find myself grappling with desi ...

The `Ext.create` function yields a constructor rather than an object as

Ext.application({ name: 'example', launch: function() { var panel = Ext.create('Ext.panel.Panel', { id:'myPanel', renderTo: Ext.getBody(), width: 400, ...