Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to use getters as values?

I have a system that takes some X and Y values for drawing stuff on a canvas. Now, I want a way to set the X or Y of one of the components to a non-static value, by setting its value to a function.

For example, instead of writing something like: rect.w = 50;

I would write rect.w = () => 50 + score; in order to make the score manipulate the width of the rectangle.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I started writing a TypeScript type definition for these kinds of parameters, but before I actually started implementing it in my code, I realized that this probably isn’t a good idea. I’ll have to constantly check if these values are functions or numbers any time I need to use them. On the other hand, JS getters, which act like object properties while really just being syntactic sugar for methods, are the perfect answer for this case, but they’re meant for objects. Is there a way to implement something like getters for values?

Looking for something like:

rect.w = 50;              // valid
rect.w = get () => 50;    // valid, functionally same as above (but pointless)
rect.w = get () => x;     // valid, rect.w returns (() => x)() when checked, acts like a pointer does in other languages
rect.w = get () => 50 + x // valid, rect.w returns (() => x + 50)()

>Solution :

Ok you want to use Object.defineProperty()

const rect = {
  x: 99
};

Object.defineProperty(rect , 'w', { get() { return this.x + 50 } });

console.log(rect.w);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading