装饰器 - @decorator

// accessor 将字段定义到原型上

Stage 3,跟以前的 TS 装饰器很像了,区别是非 class 装饰器不能直接取得 prototype



建议已经更新,强化了以前的功能
定义装饰器:
function defineElement(tagName) {
return function(classDescriptor) {
let { kind, elements } = classDescriptor;
assert(kind == "class");
return {
kind,
elements,
finisher(klass) {
window.customElements.define(tagName, klass);
}
};
};
}

  • Descriptor Class
  • Public/Private static method
  • Public/Private static field
  • Public/Private static accessor
  • Public/Private prototype method
  • Public/Private instance field
  • Public/Private prototype accessor

Advantages:

  • Users write class literals and explicitly annotate the piece of source code that is being manipulated, rather than spooky action-at-a-distance where a big object is passed into a special application-dependent class framework.
  • Decorators can manipulate private fields and private methods, whereas operations on objects are unable to manipulate the definitions of private names.
  • Decorators do their manipulations at the time the class is defined, rather than when instances are being created and used, so they may lead to patterns which are more amenable to efficient implementation.



用在类上时,相当于包装函数
function isAnimal(target) {
target.isAnimal = true;
return target;
}
@isAnimal
class Cat {
...
}
console.log(Cat.isAnimal); // true

用在属性上时,相当于 Object.defineProperty 函数
function readonly(target, name, descriptor) {
discriptor.writable = false;
return discriptor;
}
class Cat {
@readonly
say() {
console.log("meow ~");
}
}
var kitty = new Cat();
kitty.say = function() {
console.log("woof !");
}
kitty.say() // meow ~