Is it possible to programmatically include a getter method to a class in JavaScript or TypeScript?

My current focus is on TypeScript and I'm exploring the decorators functionality. I would greatly appreciate some guidance or expert knowledge on JavaScript capabilities in this area.

I am curious about dynamically adding a getter method to a Prototype object so that it can be executed instead of directly accessing a property on an instance.

Let's consider the following code:

class Car {
  @decorate
  color: string = 'red';

  drive() {
    return 'Driving';
  }
}


function decorate(target, key) {
  // It would be interesting to add a getter and update
  // the target prototype to include such a getter
  // I understand this specific implementation won't work, but it illustrates the concept.
  target[key] = function() {
    console.log(`Accessing property: ${key}`);
    return eval(`this.${key}`)
  }
}

When creating an object and trying to access .color, for example:

const car = new Car();
car.color;

Ideally, the console output should be:

Accessing property: color

Answer №1

JavaScript provides the Proxy feature for object manipulation. According to MDN, Proxy allows the creation of an object that can replace the original object while redefining important Object operations such as property access, setting, and definition. Proxy objects are commonly used for tasks like logging property accesses, validation, input formatting, and data sanitization.

class Bicycle {
  color = 'blue'

  ride() {
    return 'Riding'
  }
}

const proxyBike = new Proxy(new Bicycle(), {
   get(target, key) {
      console.log(`Property accessed: ${key}`);
      return Reflect.get(target, key)
   }
})

proxyBike.color // outputs "Property accessed: color" and returns the value of color.

Answer №2

If you're looking to enhance an object using plain javascript, one useful approach is utilizing Object.defineProperty to dynamically introduce getters and setters.

This methodology forms the basis of my initial response.

In scenarios where you only want to modify particular fields within the object, following MDN's illustration may be the most straightforward technique:

const o = {a: 0};  
Object.defineProperty(o, 'b', { get() { return this.a + 1; } });  
console.log(o.b) // Activates the getter, resulting in a + 1 (which equals 1)  

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

Sharing information among v-for divisions - Vue.js

I am currently delving into the world of VueJS. While my code may not be the most elegant, it does the job almost as intended. The issue I am facing is that the API provides the title and href separately in different v-for loops, even though each loop only ...

Why is there a node_modules folder present in the npm package I authored when using it as a dependency in another module?

After successfully launching my first npm package, I noticed something strange when installing it as a dependency in my project. Upon exploring the project folder in node_modules, I discovered an unexpected node_modules folder containing just one package ...

Retrieving data from an external API using Express.js and displaying it on a website

I'm facing a challenge in handling a solution with node.js and express.js utilizing pug for rendering HTML. I need to render on a single page by retrieving values from separate HTTP GET requests from different websites. My goal is for express/node to ...

Is there a way to transfer the functionality of openssl_seal from PHP to NodeJS 18?

I'm looking to convert the openssl_seal() function from PHP to NodeJs. The code below is from my PHP SDK and works flawlessly, which is what I want to migrate: $ivLength = openssl_cipher_iv_length('AES-256-CBC') ?: 16; $iv = openssl_random ...

The length function appears to be signaling an unanticipated error

Recently, I encountered an issue with the code execution. Although the code appears to be functioning correctly, it is throwing an uncaught error. Is there a reason for concern regarding this situation? var xmlhttp = new XMLHttpRequest(); xmlhttp.onread ...

Swap out the HTML button element for text once the form is submitted

On the main page, I have a button that opens a modal when clicked. Inside the modal, there is a form with a submit button that closes the modal and returns to the main page. After closing the modal, I want to change the HTML button on the main page to plai ...

Unable to establish a connection with the endpoint

I'm encountering an issue while trying to connect to the endpoint on the server. Below is the code snippet: Register.jsx function Register() { const [registerUser, setRegisterUser] = useState({ username: "", email: "", password: "", ...

Is concealing content using Javascript or jQuery worth exploring?

While I have been hiding content using display:none; in css, there are concerns that Google may not like this approach. However, due to the needs of jQuery animations, it has been necessary for me. Recently, I have come across a new method for hiding conte ...

No error reported upon trying to render json output

I'm having an issue where the following code is not displaying any output. Can someone help me identify what mistake I might be making? This is the HTML file: <head> <script type = "text/javascript"> function ajax_get_json() { var h ...

Pictures are not showing up in the gallery after they have been saved

if (action.equals("saveToGallery")) { JSONObject obj = args.getJSONObject(0); String imageSource = obj.has("imageSrc") ? obj.getString("imageSrc") : null; String imageName = obj.has(" ...

Introducing Vee Validate 3.x and the ValidationFlags data type definition

I'm currently struggling to locate and utilize the ValidationFlags type within Vee-Validate 3. Despite my efforts, I am encountering difficulties in importing it. I am aware that this type is present in the source code located here. However, when I a ...

Error: Unable to locate module '@/components/Header' in Next.js project

I'm currently facing an issue while working on my Next.js project. The problem arises when I attempt to import a component into my 'page.js' file. In the 'src' folder, I have a subdirectory named 'components' which contai ...

Could you please ensure that the animation activates upon hovering over the "a" element?

Utilizing bootstrap, I have created the following code. I am looking to add functionality that triggers an animation upon mouseover of an img or a element, and stops the animation upon mouseleave. .progress-bar { animation: pr 2s infinite; } @keyfr ...

The function cannot be applied to the size of the map within the action payload

Is there a way to replace the for loop with the map method? The data structure for book.pages is in the format [{},{},{}] I tried using the size method and included this line console.log("book.pages.map.size();--->", book.pages.map.si ...

I encountered a problem with routing in my MERN project while trying to implement a feature I learned from a YouTube tutorial

My first question on stackoverflow. To summarize: I followed a YouTube video and downloaded the course code from the GitHub link provided, but I'm encountering routing issues despite reading similar questions on stackoverflow. I've been followi ...

Guide to successfully integrate MathJax into your React application

I developed an application using HTML that successfully rendered MathJax equations through a script tag. However, after transitioning to React, the MathJax equations are no longer appearing. I have tried adding the MathJax script (shown below) in the comp ...

What is the best approach to building this using Angular?

Greetings, this marks the beginning of my inquiry and I must admit that articulating it correctly might be a challenge. Nevertheless, here's my attempt: Within the following code snippet, there lies an element that effectively fills up my designated ...

Is it possible to use tabs.create to generate a tab and then inject a content script, where the code attribute is effective but the file attribute seems to be ineffective

I am currently facing an issue with injecting a content script file into a newly created tab. The problem lies in the fact that I keep receiving an error stating chrome.tabs.executeScript(...) is undefined in the console output of the Popup. It may be wort ...

Sending data from configuration to factory in AngularJS and UI Router

Trying to perform a search in an http call with a dynamic value based on the current view. The factory setup is as follows: .factory('SearchService', ['$http','$filter', function($http, $filter) { var service = { get ...

Fetching deeply nested data from JSON within Angular Material tables - ANGULAR

Having trouble retrieving data from localhost, especially when it's in a different structure. Any suggestions on how to properly extract and display this data for the user? This is my attempted approach, but I'm encountering an error message: ER ...