Function as getter/setter

Can property getter/setter be implemented as a function?

Traditional getter/setters work like this:

class Test {
  something: any;

  get prop() {
    return something;
  }
  set prop(value) {
    something = value;
  }
}

let instance = new Test();
instance.prop = 'Foo';
console.log(instance.prop); // = Foo

I am looking for the following functionality:

let instance = new Test();
instance.prop('Bar') = 'Foo'; // accessing setter as a function of prop
console.log(instance.prop('Bar')); // = Foo

I understand that this is not a common usage and there are other ways to achieve similar results. I am just curious if this can be done in JS/TS/ES6.

Update

This is the closest solution I could find:

class Test {
  something: any;

  prop(area /* my custom symbol type */) {
    const obj: any = {};
    Object.defineProperty(obj, 'value', {
      // retrieve child object of my complex object
      get: () => this.something[area];
      // update part of my complex object
      set: (value) => {
        this.something = {...this.something, [area]: value}
      }
    });
  }
}

let instance = new Test();
instance.prop('Bar').value = 'Foo';
console.log(instance.prop('Bar').value); // = Foo

In summary, I would like to eliminate the need for the suffix value if possible.

Answer №1

Like @deceze pointed out in the initial comment, you cannot assign to a function call. Therefore, the solution provided in the update is the most optimal.

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

Are there any jQuery Context Menu plugins clever enough to handle window borders seamlessly?

After reviewing UIkit, as well as some other jQuery Context Menu plugins, I have noticed that they all tend to exhibit a similar behavior: The actual menu div renders outside the window, causing valuable content to be hidden from view. Is there a way to ...

Using Jquery's $.each() method within an ajax call can be a powerful

Is it possible for a jQuery each loop to wait for Ajax success before continuing when sending SMS to recipients from an object? I want my script to effectively send one SMS, display a success message on the DOM, and then proceed with the next recipient. O ...

How can you identify the second least common integer in an array of numbers?

Seeking help with a JavaScript coding challenge that I'm stuck on, here is the question: Create a function that takes an array of integers and returns an element from that array. The function should calculate the frequency of each element (how many ...

Tips for creating reusable React components

In my current project, I am utilizing React. One of the tasks at hand is to create a reusable component called Input. Below is the code snippet: import React from "react"; import TextField from "@material-ui/core/TextField"; const Input = ({ name, val ...

Handling errors in image echo in PHP

My attempts to manage 404 images retrieved from omdbapi.com have failed due to issues in my code. I am currently looping through an array to create a movie list. echo '<a href="'.$oIMDB->getUrl().'" target="_new"><img class="i ...

Automatically formatting text upon entering it in Vue.js

I need assistance with auto-formatting the postal code entered by the user. The rule for the postal code is to use the format A0A 0A0 or 12345. If the user inputs a code like L9V0C7, it should automatically reformat to L9V 0C7. However, if the postal code ...

Utilizing discriminated unions in conjunction with classes: A step-by-step guide

I'm having an issue converting a discriminated union into a string. The union comprises two interfaces. When I use the function with a simple object that matches one of the interfaces, I get the desired output. However, if I use a class that implement ...

I encountered an error stating that "paypal is not defined" while configuring PayPal Checkout with vue.js

Recently, I created a component called PaypalButton.vue. I followed the instructions provided here to implement the button: https://developer.paypal.com/docs/checkout/integrate/# <template> <div> <div id="paypal-button-container&q ...

Creating a spherical shape using random particles in three.js

Can anyone assist me in creating a random sphere using particles in three.js? I can create different shapes with particles, but I'm unsure how to generate them randomly. Here's my current code: // point cloud geometry var geometry = new THREE. ...

What Could be causing the Electron Vibrancy Effect to be malfunctioning?

This issue is really baffling me because I can't pinpoint where the problem lies. In my previous project using older versions of Electron on the same machine, everything worked fine when I used vibrancy. But now, it's not working and I have no c ...

Ways to showcase the resulting answer using vue.js?

My current query is regarding the display of error messages. How can I show the error message "passwords do not match" {"errors": {"password": ["Passwords donot match"]}, "status": false, "msg": "Validation erro", "error-type": 0} In my code snippet, I h ...

Transferring an array of objects from JavaScript to PHP using AJAX with jQuery and JSON

Showcased below is a piece of javascript code: var jsonData = JSON.stringify(testObj); $.ajax({ url: '../php/functions/spesific_field_set.php', type: 'post', data: {fieldObjArray: j ...

Rate variable input

After creating my custom function to fetch data from an API in order to change the user's pace, I defined the changePace function with a parameter named "pace". This parameter will be determined based on the user's selection of one of four paces: ...

It is necessary to render React Native text strings within a text component

Greetings! The React Native code snippet below is responsible for rendering a user interface. However, upon running the code, an error occurred. How can I resolve this issue? The error message indicates that text strings must be rendered within a text comp ...

Sharing and showcasing files directly from a local directory

Recently diving into NodeJS and web development, I've successfully used multer to upload a single file within my web application. The file gets uploaded to my "uploads" folder flawlessly, and now I'm planning on storing the file path in my databa ...

Transitioning from es2016 to es2018 or later versions may cause fakeAsync tests to encounter failures

I have been working on upgrading my project and wanted to make sure I was using the latest ECMAScript version. In my tsconfig.spec.json files, I originally had es2016, but I decided to try updating it to 2018 and even experimented with es2022. After chan ...

Develop a custom time input mask in AngularJS controller

In my AngularJS controller, I have the following code snippet: $scope.detailConfig = [{ title: $filter('translate')('bundle.app.HORA_MINUTO_INICIAL_DESCONSIDERAR'), property: 'faixaHorariaInicial', type: ' ...

What is the best way to organize code into separate files while utilizing a module that needs to be included in every file?

In this particular scenario, I am utilizing a headless browser with Puppeteer Chrome and MongoDB. Take a look at the following code snippet: var browser = await puppeteer.launch() var page = await browser.newPage() var db = await MongoClient.connect(" ...

Generating visual content from an application programming interface

<div class="row box"> <div class="col-md-4 pic"></div> <div id="temperature" class="col-md-4 change make_blue bigger_text"> Placeholder </div> <div class="col-md-4"> <button id="getChange" class="make_ ...

Tracking and managing user clicks on external links within a vue.js application

I am currently working on a web application that retrieves data from a CMS. Utilizing the Vue-Router in 'history' mode, I need to address content fetched from the API which may include links. My goal is to manage specific links using the router w ...