Exploring EcmaScript Decorators
Addy Osmani
76419
Unfortunately it’s impossible to call original decorated function with context of object instance and that makes it particular useful
Assume we have simple Cat class similar to your example:
class Cat {
constructor(name) {
this.name = name
}
@somedecorator
meow() { return `${this.name} says Meow!` }
}
// And we’d like to extend result of the meow call
function somedecorator(target, name, descriptor) {
// target is Cat prototype here and not the instance
var fn = descriptor.value;
descriptor.value = function () {
var result = fn.call(target) // returns “undefined says Meow!”
return result + ‘ add something from decorator’
}
return descriptor;
}