Home > Software design >  Is there a way to use getters as values?
Is there a way to use getters as values?

Time:08-30

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.

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)()

CodePudding user response:

Ok you want to use Object.defineProperty()

const rect = {
  x: 99
};

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

console.log(rect.w);

  • Related