装饰器

[说明] Decorator 提案经历了重大的语法变化,目前处于第三阶段,定案之前不知道是否还有变化。本章现在属于草稿阶段,凡是标注“新语法”的章节,都是基于当前的语法,不过没有详细整理,只是一些原始材料;未标注“新语法”的章节基于以前的语法,是过去遗留的稿子。之所以保留以前的内容,有两个原因,一是 TypeScript 装饰器会用到这些语法,二是里面包含不少有价值的内容。等到标准完全定案,本章将彻底重写:删去过时内容,补充材料,增加解释。(2022年6月)

简介(新语法)

装饰器(Decorator)用来增强 JavaScript 类(class)的功能,许多面向对象的语言都有这种语法,目前有一个提案将其引入了 ECMAScript。

装饰器是一种函数,写成@ + 函数名,可以用来装饰四种类型的值。

  • 类的属性
  • 类的方法
  • 属性存取器(accessor)

下面的例子是装饰器放在类名和类方法名之前,大家可以感受一下写法。

  1. @frozen class Foo {
  2. @configurable(false)
  3. @enumerable(true)
  4. method() {}
  5. @throttle(500)
  6. expensiveMethod() {}
  7. }

上面代码一共使用了四个装饰器,一个用在类本身(@frozen),另外三个用在类方法(@configurable()、@enumerable()、@throttle())。它们不仅增加了代码的可读性,清晰地表达了意图,而且提供一种方便的手段,增加或修改类的功能。

装饰器 API(新语法)

装饰器是一个函数,API 的类型描述如下(TypeScript 写法)。

  1. type Decorator = (value: Input, context: {
  2. kind: string;
  3. name: string | symbol;
  4. access: {
  5. get?(): unknown;
  6. set?(value: unknown): void;
  7. };
  8. private?: boolean;
  9. static?: boolean;
  10. addInitializer?(initializer: () => void): void;
  11. }) => Output | void;

装饰器函数有两个参数。运行时,JavaScript 引擎会提供这两个参数。

  • value:所要装饰的值,某些情况下可能是undefined(装饰属性时)。
  • context:上下文信息对象。

装饰器函数的返回值,是一个新版本的装饰对象,但也可以不返回任何值(void)。

context对象有很多属性,其中kind属性表示属于哪一种装饰,其他属性的含义如下。

  • kind:字符串,表示装饰类型,可能的取值有classmethodgettersetterfieldaccessor
  • name:被装饰的值的名称: The name of the value, or in the case of private elements the description of it (e.g. the readable name).
  • access:对象,包含访问这个值的方法,即存值器和取值器。
  • static: 布尔值,该值是否为静态元素。
  • private:布尔值,该值是否为私有元素。
  • addInitializer:函数,允许用户增加初始化逻辑。

装饰器的执行步骤如下。

  1. 计算各个装饰器的值,按照从左到右,从上到下的顺序。
  2. 调用方法装饰器。
  3. 调用类装饰器。

类的装饰

装饰器可以用来装饰整个类。

  1. @testable
  2. class MyTestableClass {
  3. // ...
  4. }
  5. function testable(target) {
  6. target.isTestable = true;
  7. }
  8. MyTestableClass.isTestable // true

上面代码中,@testable就是一个装饰器。它修改了MyTestableClass这个类的行为,为它加上了静态属性isTestabletestable函数的参数targetMyTestableClass类本身。

基本上,装饰器的行为就是下面这样。

  1. @decorator
  2. class A {}
  3. // 等同于
  4. class A {}
  5. A = decorator(A) || A;

也就是说,装饰器是一个对类进行处理的函数。装饰器函数的第一个参数,就是所要装饰的目标类。

  1. function testable(target) {
  2. // ...
  3. }

上面代码中,testable函数的参数target,就是会被装饰的类。

如果觉得一个参数不够用,可以在装饰器外面再封装一层函数。

  1. function testable(isTestable) {
  2. return function(target) {
  3. target.isTestable = isTestable;
  4. }
  5. }
  6. @testable(true)
  7. class MyTestableClass {}
  8. MyTestableClass.isTestable // true
  9. @testable(false)
  10. class MyClass {}
  11. MyClass.isTestable // false

上面代码中,装饰器testable可以接受参数,这就等于可以修改装饰器的行为。

注意,装饰器对类的行为的改变,是代码编译时发生的,而不是在运行时。这意味着,装饰器能在编译阶段运行代码。也就是说,装饰器本质就是编译时执行的函数。

前面的例子是为类添加一个静态属性,如果想添加实例属性,可以通过目标类的prototype对象操作。

  1. function testable(target) {
  2. target.prototype.isTestable = true;
  3. }
  4. @testable
  5. class MyTestableClass {}
  6. let obj = new MyTestableClass();
  7. obj.isTestable // true

上面代码中,装饰器函数testable是在目标类的prototype对象上添加属性,因此就可以在实例上调用。

下面是另外一个例子。

  1. // mixins.js
  2. export function mixins(...list) {
  3. return function (target) {
  4. Object.assign(target.prototype, ...list)
  5. }
  6. }
  7. // main.js
  8. import { mixins } from './mixins.js'
  9. const Foo = {
  10. foo() { console.log('foo') }
  11. };
  12. @mixins(Foo)
  13. class MyClass {}
  14. let obj = new MyClass();
  15. obj.foo() // 'foo'

上面代码通过装饰器mixins,把Foo对象的方法添加到了MyClass的实例上面。可以用Object.assign()模拟这个功能。

  1. const Foo = {
  2. foo() { console.log('foo') }
  3. };
  4. class MyClass {}
  5. Object.assign(MyClass.prototype, Foo);
  6. let obj = new MyClass();
  7. obj.foo() // 'foo'

实际开发中,React 与 Redux 库结合使用时,常常需要写成下面这样。

  1. class MyReactComponent extends React.Component {}
  2. export default connect(mapStateToProps, mapDispatchToProps)(MyReactComponent);

有了装饰器,就可以改写上面的代码。

  1. @connect(mapStateToProps, mapDispatchToProps)
  2. export default class MyReactComponent extends React.Component {}

相对来说,后一种写法看上去更容易理解。

类装饰器(新语法)

类装饰器的类型描述如下。

  1. type ClassDecorator = (value: Function, context: {
  2. kind: "class";
  3. name: string | undefined;
  4. addInitializer(initializer: () => void): void;
  5. }) => Function | void;

类装饰器的第一个参数,就是被装饰的类。第二个参数是上下文对象,如果被装饰的类是一个匿名类,name属性就为undefined

类装饰器可以返回一个新的类,取代原来的类,也可以不返回任何值。如果返回的不是构造函数,就会报错。

下面是一个例子。

  1. function logged(value, { kind, name }) {
  2. if (kind === "class") {
  3. return class extends value {
  4. constructor(...args) {
  5. super(...args);
  6. console.log(`constructing an instance of ${name} with arguments ${args.join(", ")}`);
  7. }
  8. }
  9. }
  10. // ...
  11. }
  12. @logged
  13. class C {}
  14. new C(1);
  15. // constructing an instance of C with arguments 1

如果不使用装饰器,类装饰器实际上执行的是下面的语法。

  1. class C {}
  2. C = logged(C, {
  3. kind: "class",
  4. name: "C",
  5. }) ?? C;
  6. new C(1);

方法装饰器(新语法)

方法装饰器会修改类的方法。

  1. class C {
  2. @trace
  3. toString() {
  4. return 'C';
  5. }
  6. }
  7. // 相当于
  8. C.prototype.toString = trace(C.prototype.toString);

上面示例中,@trace装饰toString()方法,就相当于修改了该方法。

方法装饰器使用 TypeScript 描述类型如下。

  1. type ClassMethodDecorator = (value: Function, context: {
  2. kind: "method";
  3. name: string | symbol;
  4. access: { get(): unknown };
  5. static: boolean;
  6. private: boolean;
  7. addInitializer(initializer: () => void): void;
  8. }) => Function | void;

方法装饰器的第一个参数value,就是所要装饰的方法。

方法装饰器可以返回一个新函数,取代原来的方法,也可以不返回值,表示依然使用原来的方法。如果返回其他类型的值,就会报错。下面是一个例子。

  1. function replaceMethod() {
  2. return function () {
  3. return `How are you, ${this.name}?`;
  4. }
  5. }
  6. class Person {
  7. constructor(name) {
  8. this.name = name;
  9. }
  10. @replaceMethod
  11. hello() {
  12. return `Hi ${this.name}!`;
  13. }
  14. }
  15. const robin = new Person('Robin');
  16. robin.hello(), 'How are you, Robin?'

上面示例中,@replaceMethod返回了一个新函数,取代了原来的hello()方法。

  1. function logged(value, { kind, name }) {
  2. if (kind === "method") {
  3. return function (...args) {
  4. console.log(`starting ${name} with arguments ${args.join(", ")}`);
  5. const ret = value.call(this, ...args);
  6. console.log(`ending ${name}`);
  7. return ret;
  8. };
  9. }
  10. }
  11. class C {
  12. @logged
  13. m(arg) {}
  14. }
  15. new C().m(1);
  16. // starting m with arguments 1
  17. // ending m

上面示例中,装饰器@logged返回一个函数,代替原来的m()方法。

这里的装饰器实际上是一个语法糖,真正的操作是像下面这样,改掉原型链上面m()方法。

  1. class C {
  2. m(arg) {}
  3. }
  4. C.prototype.m = logged(C.prototype.m, {
  5. kind: "method",
  6. name: "m",
  7. static: false,
  8. private: false,
  9. }) ?? C.prototype.m;

方法的装饰

装饰器不仅可以装饰类,还可以装饰类的属性。

  1. class Person {
  2. @readonly
  3. name() { return `${this.first} ${this.last}` }
  4. }

上面代码中,装饰器readonly用来装饰“类”的name方法。

装饰器函数readonly一共可以接受三个参数。

  1. function readonly(target, name, descriptor){
  2. // descriptor对象原来的值如下
  3. // {
  4. // value: specifiedFunction,
  5. // enumerable: false,
  6. // configurable: true,
  7. // writable: true
  8. // };
  9. descriptor.writable = false;
  10. return descriptor;
  11. }
  12. readonly(Person.prototype, 'name', descriptor);
  13. // 类似于
  14. Object.defineProperty(Person.prototype, 'name', descriptor);

装饰器第一个参数是类的原型对象,上例是Person.prototype,装饰器的本意是要“装饰”类的实例,但是这个时候实例还没生成,所以只能去装饰原型(这不同于类的装饰,那种情况时target参数指的是类本身);第二个参数是所要装饰的属性名,第三个参数是该属性的描述对象。

另外,上面代码说明,装饰器(readonly)会修改属性的描述对象(descriptor),然后被修改的描述对象再用来定义属性。

下面是另一个例子,修改属性描述对象的enumerable属性,使得该属性不可遍历。

  1. class Person {
  2. @nonenumerable
  3. get kidCount() { return this.children.length; }
  4. }
  5. function nonenumerable(target, name, descriptor) {
  6. descriptor.enumerable = false;
  7. return descriptor;
  8. }

下面的@log装饰器,可以起到输出日志的作用。

  1. class Math {
  2. @log
  3. add(a, b) {
  4. return a + b;
  5. }
  6. }
  7. function log(target, name, descriptor) {
  8. var oldValue = descriptor.value;
  9. descriptor.value = function() {
  10. console.log(`Calling ${name} with`, arguments);
  11. return oldValue.apply(this, arguments);
  12. };
  13. return descriptor;
  14. }
  15. const math = new Math();
  16. // passed parameters should get logged now
  17. math.add(2, 4);

上面代码中,@log装饰器的作用就是在执行原始的操作之前,执行一次console.log,从而达到输出日志的目的。

装饰器有注释的作用。

  1. @testable
  2. class Person {
  3. @readonly
  4. @nonenumerable
  5. name() { return `${this.first} ${this.last}` }
  6. }

从上面代码中,我们一眼就能看出,Person类是可测试的,而name方法是只读和不可枚举的。

下面是使用 Decorator 写法的组件,看上去一目了然。

  1. @Component({
  2. tag: 'my-component',
  3. styleUrl: 'my-component.scss'
  4. })
  5. export class MyComponent {
  6. @Prop() first: string;
  7. @Prop() last: string;
  8. @State() isVisible: boolean = true;
  9. render() {
  10. return (
  11. <p>Hello, my name is {this.first} {this.last}</p>
  12. );
  13. }
  14. }

如果同一个方法有多个装饰器,会像剥洋葱一样,先从外到内进入,然后由内向外执行。

  1. function dec(id){
  2. console.log('evaluated', id);
  3. return (target, property, descriptor) => console.log('executed', id);
  4. }
  5. class Example {
  6. @dec(1)
  7. @dec(2)
  8. method(){}
  9. }
  10. // evaluated 1
  11. // evaluated 2
  12. // executed 2
  13. // executed 1

上面代码中,外层装饰器@dec(1)先进入,但是内层装饰器@dec(2)先执行。

除了注释,装饰器还能用来类型检查。所以,对于类来说,这项功能相当有用。从长期来看,它将是 JavaScript 代码静态分析的重要工具。

为什么装饰器不能用于函数?

装饰器只能用于类和类的方法,不能用于函数,因为存在函数提升。

  1. var counter = 0;
  2. var add = function () {
  3. counter++;
  4. };
  5. @add
  6. function foo() {
  7. }

上面的代码,意图是执行后counter等于 1,但是实际上结果是counter等于 0。因为函数提升,使得实际执行的代码是下面这样。

  1. var counter;
  2. var add;
  3. @add
  4. function foo() {
  5. }
  6. counter = 0;
  7. add = function () {
  8. counter++;
  9. };

下面是另一个例子。

  1. var readOnly = require("some-decorator");
  2. @readOnly
  3. function foo() {
  4. }

上面代码也有问题,因为实际执行是下面这样。

  1. var readOnly;
  2. @readOnly
  3. function foo() {
  4. }
  5. readOnly = require("some-decorator");

总之,由于存在函数提升,使得装饰器不能用于函数。类是不会提升的,所以就没有这方面的问题。

另一方面,如果一定要装饰函数,可以采用高阶函数的形式直接执行。

  1. function doSomething(name) {
  2. console.log('Hello, ' + name);
  3. }
  4. function loggingDecorator(wrapped) {
  5. return function() {
  6. console.log('Starting');
  7. const result = wrapped.apply(this, arguments);
  8. console.log('Finished');
  9. return result;
  10. }
  11. }
  12. const wrapped = loggingDecorator(doSomething);

存取器装饰器(新语法)

存取器装饰器使用 TypeScript 描述的类型如下。

  1. type ClassGetterDecorator = (value: Function, context: {
  2. kind: "getter";
  3. name: string | symbol;
  4. access: { get(): unknown };
  5. static: boolean;
  6. private: boolean;
  7. addInitializer(initializer: () => void): void;
  8. }) => Function | void;
  9. type ClassSetterDecorator = (value: Function, context: {
  10. kind: "setter";
  11. name: string | symbol;
  12. access: { set(value: unknown): void };
  13. static: boolean;
  14. private: boolean;
  15. addInitializer(initializer: () => void): void;
  16. }) => Function | void;

存取器装饰器的第一个参数就是原始的存值器(setter)和取值器(getter)。

存取器装饰器的返回值如果是一个函数,就会取代原来的存取器。本质上,就像方法装饰器一样,修改发生在类的原型对象上。它也可以不返回任何值,继续使用原来的存取器。如果返回其他类型的值,就会报错。

存取器装饰器对存值器(setter)和取值器(getter)是分开作用的。下面的例子里面,@foo只装饰get x(),不装饰set x()

  1. class C {
  2. @foo
  3. get x() {
  4. // ...
  5. }
  6. set x(val) {
  7. // ...
  8. }
  9. }

上一节的@logged装饰器稍加修改,就可以用在存取装饰器。

  1. function logged(value, { kind, name }) {
  2. if (kind === "method" || kind === "getter" || kind === "setter") {
  3. return function (...args) {
  4. console.log(`starting ${name} with arguments ${args.join(", ")}`);
  5. const ret = value.call(this, ...args);
  6. console.log(`ending ${name}`);
  7. return ret;
  8. };
  9. }
  10. }
  11. class C {
  12. @logged
  13. set x(arg) {}
  14. }
  15. new C().x = 1
  16. // starting x with arguments 1
  17. // ending x

如果去掉语法糖,使用传统语法来写,就是改掉了类的原型链。

  1. class C {
  2. set x(arg) {}
  3. }
  4. let { set } = Object.getOwnPropertyDescriptor(C.prototype, "x");
  5. set = logged(set, {
  6. kind: "setter",
  7. name: "x",
  8. static: false,
  9. private: false,
  10. }) ?? set;
  11. Object.defineProperty(C.prototype, "x", { set });

属性装饰器(新语法)

属性装饰器的类型描述如下。

  1. type ClassFieldDecorator = (value: undefined, context: {
  2. kind: "field";
  3. name: string | symbol;
  4. access: { get(): unknown, set(value: unknown): void };
  5. static: boolean;
  6. private: boolean;
  7. }) => (initialValue: unknown) => unknown | void;

属性装饰器的第一个参数是undefined,即不输入值。用户可以选择让装饰器返回一个初始化函数,当该属性被赋值时,这个初始化函数会自动运行,它会收到属性的初始值,然后返回一个新的初始值。属性装饰器也可以不返回任何值。除了这两种情况,返回其他类型的值都会报错。

下面是一个例子。

  1. function logged(value, { kind, name }) {
  2. if (kind === "field") {
  3. return function (initialValue) {
  4. console.log(`initializing ${name} with value ${initialValue}`);
  5. return initialValue;
  6. };
  7. }
  8. // ...
  9. }
  10. class C {
  11. @logged x = 1;
  12. }
  13. new C();
  14. // initializing x with value 1

如果不使用装饰器语法,属性装饰器的实际作用如下。

  1. let initializeX = logged(undefined, {
  2. kind: "field",
  3. name: "x",
  4. static: false,
  5. private: false,
  6. }) ?? (initialValue) => initialValue;
  7. class C {
  8. x = initializeX.call(this, 1);
  9. }

accessor 命令(新语法)

类装饰器引入了一个新命令accessor,用来属性的前缀。

  1. class C {
  2. accessor x = 1;
  3. }

它是一种简写形式,相当于声明属性x是私有属性#x的存取接口。上面的代码等同于下面的代码。

  1. class C {
  2. #x = 1;
  3. get x() {
  4. return this.#x;
  5. }
  6. set x(val) {
  7. this.#x = val;
  8. }
  9. }

accessor命令前面,还可以加上static命令和private命令。

  1. class C {
  2. static accessor x = 1;
  3. accessor #y = 2;
  4. }

accessor命令前面还可以接受属性装饰器。

  1. function logged(value, { kind, name }) {
  2. if (kind === "accessor") {
  3. let { get, set } = value;
  4. return {
  5. get() {
  6. console.log(`getting ${name}`);
  7. return get.call(this);
  8. },
  9. set(val) {
  10. console.log(`setting ${name} to ${val}`);
  11. return set.call(this, val);
  12. },
  13. init(initialValue) {
  14. console.log(`initializing ${name} with value ${initialValue}`);
  15. return initialValue;
  16. }
  17. };
  18. }
  19. // ...
  20. }
  21. class C {
  22. @logged accessor x = 1;
  23. }
  24. let c = new C();
  25. // initializing x with value 1
  26. c.x;
  27. // getting x
  28. c.x = 123;
  29. // setting x to 123

上面的示例等同于使用@logged装饰器,改写accessor属性的 getter 和 setter 方法。

用于accessor的属性装饰器的类型描述如下。

  1. type ClassAutoAccessorDecorator = (
  2. value: {
  3. get: () => unknown;
  4. set(value: unknown) => void;
  5. },
  6. context: {
  7. kind: "accessor";
  8. name: string | symbol;
  9. access: { get(): unknown, set(value: unknown): void };
  10. static: boolean;
  11. private: boolean;
  12. addInitializer(initializer: () => void): void;
  13. }
  14. ) => {
  15. get?: () => unknown;
  16. set?: (value: unknown) => void;
  17. initialize?: (initialValue: unknown) => unknown;
  18. } | void;

accessor命令的第一个参数接收到的是一个对象,包含了accessor命令定义的属性的存取器 get 和 set。属性装饰器可以返回一个新对象,其中包含了新的存取器,用来取代原来的,即相当于拦截了原来的存取器。此外,返回的对象还可以包括一个initialize函数,用来改变私有属性的初始值。装饰器也可以不返回值,如果返回的是其他类型的值,或者包含其他属性的对象,就会报错。

addInitializer() 方法(新语法)

除了属性装饰器,其他装饰器的上下文对象还包括一个addInitializer()方法,用来完成初始化操作。

它的运行时间如下。

  • 类装饰器:在类被完全定义之后。
  • 方法装饰器:在类构造期间运行,在属性初始化之前。
  • 静态方法装饰器:在类定义期间运行,早于静态属性定义,但晚于类方法的定义。

下面是一个例子。

  1. function customElement(name) {
  2. return (value, { addInitializer }) => {
  3. addInitializer(function() {
  4. customElements.define(name, this);
  5. });
  6. }
  7. }
  8. @customElement('my-element')
  9. class MyElement extends HTMLElement {
  10. static get observedAttributes() {
  11. return ['some', 'attrs'];
  12. }
  13. }

上面的代码等同于下面不使用装饰器的代码。

  1. class MyElement {
  2. static get observedAttributes() {
  3. return ['some', 'attrs'];
  4. }
  5. }
  6. let initializersForMyElement = [];
  7. MyElement = customElement('my-element')(MyElement, {
  8. kind: "class",
  9. name: "MyElement",
  10. addInitializer(fn) {
  11. initializersForMyElement.push(fn);
  12. },
  13. }) ?? MyElement;
  14. for (let initializer of initializersForMyElement) {
  15. initializer.call(MyElement);
  16. }

下面是方法装饰器的例子。

  1. function bound(value, { name, addInitializer }) {
  2. addInitializer(function () {
  3. this[name] = this[name].bind(this);
  4. });
  5. }
  6. class C {
  7. message = "hello!";
  8. @bound
  9. m() {
  10. console.log(this.message);
  11. }
  12. }
  13. let { m } = new C();
  14. m(); // hello!

上面的代码等同于下面不使用装饰器的代码。

  1. class C {
  2. constructor() {
  3. for (let initializer of initializersForM) {
  4. initializer.call(this);
  5. }
  6. this.message = "hello!";
  7. }
  8. m() {}
  9. }
  10. let initializersForM = []
  11. C.prototype.m = bound(
  12. C.prototype.m,
  13. {
  14. kind: "method",
  15. name: "m",
  16. static: false,
  17. private: false,
  18. addInitializer(fn) {
  19. initializersForM.push(fn);
  20. },
  21. }
  22. ) ?? C.prototype.m;

core-decorators.js

core-decorators.js是一个第三方模块,提供了几个常见的装饰器,通过它可以更好地理解装饰器。

(1)@autobind

autobind装饰器使得方法中的this对象,绑定原始对象。

  1. import { autobind } from 'core-decorators';
  2. class Person {
  3. @autobind
  4. getPerson() {
  5. return this;
  6. }
  7. }
  8. let person = new Person();
  9. let getPerson = person.getPerson;
  10. getPerson() === person;
  11. // true

(2)@readonly

readonly装饰器使得属性或方法不可写。

  1. import { readonly } from 'core-decorators';
  2. class Meal {
  3. @readonly
  4. entree = 'steak';
  5. }
  6. var dinner = new Meal();
  7. dinner.entree = 'salmon';
  8. // Cannot assign to read only property 'entree' of [object Object]

(3)@override

override装饰器检查子类的方法,是否正确覆盖了父类的同名方法,如果不正确会报错。

  1. import { override } from 'core-decorators';
  2. class Parent {
  3. speak(first, second) {}
  4. }
  5. class Child extends Parent {
  6. @override
  7. speak() {}
  8. // SyntaxError: Child#speak() does not properly override Parent#speak(first, second)
  9. }
  10. // or
  11. class Child extends Parent {
  12. @override
  13. speaks() {}
  14. // SyntaxError: No descriptor matching Child#speaks() was found on the prototype chain.
  15. //
  16. // Did you mean "speak"?
  17. }

(4)@deprecate (别名@deprecated)

deprecatedeprecated装饰器在控制台显示一条警告,表示该方法将废除。

  1. import { deprecate } from 'core-decorators';
  2. class Person {
  3. @deprecate
  4. facepalm() {}
  5. @deprecate('We stopped facepalming')
  6. facepalmHard() {}
  7. @deprecate('We stopped facepalming', { url: 'http://knowyourmeme.com/memes/facepalm' })
  8. facepalmHarder() {}
  9. }
  10. let person = new Person();
  11. person.facepalm();
  12. // DEPRECATION Person#facepalm: This function will be removed in future versions.
  13. person.facepalmHard();
  14. // DEPRECATION Person#facepalmHard: We stopped facepalming
  15. person.facepalmHarder();
  16. // DEPRECATION Person#facepalmHarder: We stopped facepalming
  17. //
  18. // See http://knowyourmeme.com/memes/facepalm for more details.
  19. //

(5)@suppressWarnings

suppressWarnings装饰器抑制deprecated装饰器导致的console.warn()调用。但是,异步代码发出的调用除外。

  1. import { suppressWarnings } from 'core-decorators';
  2. class Person {
  3. @deprecated
  4. facepalm() {}
  5. @suppressWarnings
  6. facepalmWithoutWarning() {
  7. this.facepalm();
  8. }
  9. }
  10. let person = new Person();
  11. person.facepalmWithoutWarning();
  12. // no warning is logged

使用装饰器实现自动发布事件

我们可以使用装饰器,使得对象的方法被调用时,自动发出一个事件。

  1. const postal = require("postal/lib/postal.lodash");
  2. export default function publish(topic, channel) {
  3. const channelName = channel || '/';
  4. const msgChannel = postal.channel(channelName);
  5. msgChannel.subscribe(topic, v => {
  6. console.log('频道: ', channelName);
  7. console.log('事件: ', topic);
  8. console.log('数据: ', v);
  9. });
  10. return function(target, name, descriptor) {
  11. const fn = descriptor.value;
  12. descriptor.value = function() {
  13. let value = fn.apply(this, arguments);
  14. msgChannel.publish(topic, value);
  15. };
  16. };
  17. }

上面代码定义了一个名为publish的装饰器,它通过改写descriptor.value,使得原方法被调用时,会自动发出一个事件。它使用的事件“发布/订阅”库是Postal.js

它的用法如下。

  1. // index.js
  2. import publish from './publish';
  3. class FooComponent {
  4. @publish('foo.some.message', 'component')
  5. someMethod() {
  6. return { my: 'data' };
  7. }
  8. @publish('foo.some.other')
  9. anotherMethod() {
  10. // ...
  11. }
  12. }
  13. let foo = new FooComponent();
  14. foo.someMethod();
  15. foo.anotherMethod();

以后,只要调用someMethod或者anotherMethod,就会自动发出一个事件。

  1. $ bash-node index.js
  2. 频道: component
  3. 事件: foo.some.message
  4. 数据: { my: 'data' }
  5. 频道: /
  6. 事件: foo.some.other
  7. 数据: undefined

Mixin

在装饰器的基础上,可以实现Mixin模式。所谓Mixin模式,就是对象继承的一种替代方案,中文译为“混入”(mix in),意为在一个对象之中混入另外一个对象的方法。

请看下面的例子。

  1. const Foo = {
  2. foo() { console.log('foo') }
  3. };
  4. class MyClass {}
  5. Object.assign(MyClass.prototype, Foo);
  6. let obj = new MyClass();
  7. obj.foo() // 'foo'

上面代码之中,对象Foo有一个foo方法,通过Object.assign方法,可以将foo方法“混入”MyClass类,导致MyClass的实例obj对象都具有foo方法。这就是“混入”模式的一个简单实现。

下面,我们部署一个通用脚本mixins.js,将 Mixin 写成一个装饰器。

  1. export function mixins(...list) {
  2. return function (target) {
  3. Object.assign(target.prototype, ...list);
  4. };
  5. }

然后,就可以使用上面这个装饰器,为类“混入”各种方法。

  1. import { mixins } from './mixins.js';
  2. const Foo = {
  3. foo() { console.log('foo') }
  4. };
  5. @mixins(Foo)
  6. class MyClass {}
  7. let obj = new MyClass();
  8. obj.foo() // "foo"

通过mixins这个装饰器,实现了在MyClass类上面“混入”Foo对象的foo方法。

不过,上面的方法会改写MyClass类的prototype对象,如果不喜欢这一点,也可以通过类的继承实现 Mixin。

  1. class MyClass extends MyBaseClass {
  2. /* ... */
  3. }

上面代码中,MyClass继承了MyBaseClass。如果我们想在MyClass里面“混入”一个foo方法,一个办法是在MyClassMyBaseClass之间插入一个混入类,这个类具有foo方法,并且继承了MyBaseClass的所有方法,然后MyClass再继承这个类。

  1. let MyMixin = (superclass) => class extends superclass {
  2. foo() {
  3. console.log('foo from MyMixin');
  4. }
  5. };

上面代码中,MyMixin是一个混入类生成器,接受superclass作为参数,然后返回一个继承superclass的子类,该子类包含一个foo方法。

接着,目标类再去继承这个混入类,就达到了“混入”foo方法的目的。

  1. class MyClass extends MyMixin(MyBaseClass) {
  2. /* ... */
  3. }
  4. let c = new MyClass();
  5. c.foo(); // "foo from MyMixin"

如果需要“混入”多个方法,就生成多个混入类。

  1. class MyClass extends Mixin1(Mixin2(MyBaseClass)) {
  2. /* ... */
  3. }

这种写法的一个好处,是可以调用super,因此可以避免在“混入”过程中覆盖父类的同名方法。

  1. let Mixin1 = (superclass) => class extends superclass {
  2. foo() {
  3. console.log('foo from Mixin1');
  4. if (super.foo) super.foo();
  5. }
  6. };
  7. let Mixin2 = (superclass) => class extends superclass {
  8. foo() {
  9. console.log('foo from Mixin2');
  10. if (super.foo) super.foo();
  11. }
  12. };
  13. class S {
  14. foo() {
  15. console.log('foo from S');
  16. }
  17. }
  18. class C extends Mixin1(Mixin2(S)) {
  19. foo() {
  20. console.log('foo from C');
  21. super.foo();
  22. }
  23. }

上面代码中,每一次混入发生时,都调用了父类的super.foo方法,导致父类的同名方法没有被覆盖,行为被保留了下来。

  1. new C().foo()
  2. // foo from C
  3. // foo from Mixin1
  4. // foo from Mixin2
  5. // foo from S

Trait

Trait 也是一种装饰器,效果与 Mixin 类似,但是提供更多功能,比如防止同名方法的冲突、排除混入某些方法、为混入的方法起别名等等。

下面采用traits-decorator这个第三方模块作为例子。这个模块提供的traits装饰器,不仅可以接受对象,还可以接受 ES6 类作为参数。

  1. import { traits } from 'traits-decorator';
  2. class TFoo {
  3. foo() { console.log('foo') }
  4. }
  5. const TBar = {
  6. bar() { console.log('bar') }
  7. };
  8. @traits(TFoo, TBar)
  9. class MyClass { }
  10. let obj = new MyClass();
  11. obj.foo() // foo
  12. obj.bar() // bar

上面代码中,通过traits装饰器,在MyClass类上面“混入”了TFoo类的foo方法和TBar对象的bar方法。

Trait 不允许“混入”同名方法。

  1. import { traits } from 'traits-decorator';
  2. class TFoo {
  3. foo() { console.log('foo') }
  4. }
  5. const TBar = {
  6. bar() { console.log('bar') },
  7. foo() { console.log('foo') }
  8. };
  9. @traits(TFoo, TBar)
  10. class MyClass { }
  11. // 报错
  12. // throw new Error('Method named: ' + methodName + ' is defined twice.');
  13. // ^
  14. // Error: Method named: foo is defined twice.

上面代码中,TFooTBar都有foo方法,结果traits装饰器报错。

一种解决方法是排除TBarfoo方法。

  1. import { traits, excludes } from 'traits-decorator';
  2. class TFoo {
  3. foo() { console.log('foo') }
  4. }
  5. const TBar = {
  6. bar() { console.log('bar') },
  7. foo() { console.log('foo') }
  8. };
  9. @traits(TFoo, TBar::excludes('foo'))
  10. class MyClass { }
  11. let obj = new MyClass();
  12. obj.foo() // foo
  13. obj.bar() // bar

上面代码使用绑定运算符(::)在TBar上排除foo方法,混入时就不会报错了。

另一种方法是为TBarfoo方法起一个别名。

  1. import { traits, alias } from 'traits-decorator';
  2. class TFoo {
  3. foo() { console.log('foo') }
  4. }
  5. const TBar = {
  6. bar() { console.log('bar') },
  7. foo() { console.log('foo') }
  8. };
  9. @traits(TFoo, TBar::alias({foo: 'aliasFoo'}))
  10. class MyClass { }
  11. let obj = new MyClass();
  12. obj.foo() // foo
  13. obj.aliasFoo() // foo
  14. obj.bar() // bar

上面代码为TBarfoo方法起了别名aliasFoo,于是MyClass也可以混入TBarfoo方法了。

aliasexcludes方法,可以结合起来使用。

  1. @traits(TExample::excludes('foo','bar')::alias({baz:'exampleBaz'}))
  2. class MyClass {}

上面代码排除了TExamplefoo方法和bar方法,为baz方法起了别名exampleBaz

as方法则为上面的代码提供了另一种写法。

  1. @traits(TExample::as({excludes:['foo', 'bar'], alias: {baz: 'exampleBaz'}}))
  2. class MyClass {}