loading...

re: What is the decorator pattern? And how to implement it by JavaScript? VIEW POST

FULL DISCUSSION
 

I like this! Looking at the code and not testing it - I'm wondering if you couldn't just do:

const yellowStyle = (printer) => {
  const decorator = Object.create(printer);

  decorator.print = (text, style = '') => {
    printer.print(text, `${style}color: yellow;`);
  };

  return decorator;
};

I have a method called decorate I call often to extend objects (when I can't use Proxy as I run stuff for IE11), it's not quite the same as yours but basically extends existing object with additional properties that won't be saved.

export function decorate(target, withProps) {
    for (let key of Object.keys(withProps)) {
        Object.defineProperty(target, key, {
            get() {
                return withProps[key]
            },
            configurable: true,
        })
    }
    return target
}

This is doing something a bit different because the underlying object isn't copied but remains in place and decorated, probably not with an override.

 

Thanks for sharing!
This way is a more general than my for action of decorate something, I will try to improve my code by this function you sharing.
By the way next I will learn about proxy pattern 😆

code of conduct - report abuse