*An errata in my code*
The getter is mutating the object with a enumerable property, so
consecutives invocations of JSON.stringify will result different from
the first call (if the property is yet not initialized). The current
problem is:
```js
JSON.stringify(foo) // Returns "{"bar":3}"
// After the first bar "get" the object has now another property "_bar"
JSON.stringify(foo) // Returns "{"bar":3,"_bar":3}"
```
I did it as a quick loose scratch and didn't test it. A more robust
implementation (with a helper function) probably would use closures to
maintain the factory state. As exemplified:
```js
const defineLazyProp = (obj, propName, valueFactory) => {
  let selfDestroyingFactory = () => {
    const value = valueFactory();
    selfDestroyingFactory = () => value;
    return value;
  };

  return Object.defineProperty(obj, propName, {
    enumerable: true,
    configurable: false, // It might be discussed if the lazy prop
should be configurable or not
    get() {
      return selfDestroyingFactory();
    },
  });
};

const foo = {};

defineLazyProp(foo, 'bar', () => 3);

// This should work correctly now
console.log(JSON.stringify(foo));
console.log(JSON.stringify(foo));
```
It's a bit more verbose, but it's the best way I can think of
"ponyfilling" it at the moment.

On June 28, 02:45, Isiah Meadows <isiahmead...@gmail.com> wrote:
>
> I agree the main proposal is long and complex, but this kind of addition 
> could be designed with little effort to "fall out of the grid", since it has 
> so much in common with classes already (properties, getters/setters, 
> methods). The main question is with properties, but those are easy to just 
> leave out, since function calls do just as well.
>

You are right, but yet I prefer to get the classes decorators
advancing to a greater stage as soon as possible, a objet literal
decorator would be a easy extension to the current proposal. By the
way, I was comparing with the 2 others proposals by the fact that they
are more like "extensions" to the main proposal, not by the complexity
(as far as I know, mix the 3 decorators proposals in one would stall
most of the work), but yeah they really are different beasts.
_______________________________________________
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to