js装饰器语法

424 阅读1分钟

本质

装饰器本质就是函数,一般来说用在类和类的方法上。

装饰器在编译阶段运行代码,将类或方法作为参数传入装饰器(函数),给类或方法增加额外功能。

修饰器语法同时还有注释的作用

用在类上

@testable
class MyTestableClass {
  // ...
}

function testable(target) {
  target.isTestable = true;
}

MyTestableClass.isTestable // true

给类添加静态属性isTestable

静态属性:直接定义在类上的属性,也就是定义在构造函数上的属性(函数的属性),所以即不再实例上也不在原型上。

用在类的属性上(主要是方法)

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

function readonly(target, name, descriptor){
  // descriptor对象原来的值如下
  // {
  //   value: specifiedFunction,
  //   enumerable: false,
  //   configurable: true,
  //   writable: true
  // };
  descriptor.writable = false;
  return descriptor;
}

readonly(Person.prototype, 'name', descriptor);
// 类似于
Object.defineProperty(Person.prototype, 'name', descriptor);

name方法不能被重写了,只能读(调用)。

装饰器用在方法上可以增加一些副作用,里如只读、每次调用打log、绑定this指向、防抖、节流等。

装饰器外加封装函数

function testable(isTestable) {
  return function(target) {
    target.isTestable = isTestable;
  }
}

@testable(true)
class MyTestableClass {}
MyTestableClass.isTestable // true

@testable(false)
class MyClass {}
MyClass.isTestable // false

凡是装饰上加了参数的,都是做了装饰器外层封装的,提供更多的可操作性。

多个装饰器时的执行顺序

function dec(id){
  console.log('evaluated', id);
  return (target, property, descriptor) => console.log('executed', id);
}

class Example {
    @dec(1)
    @dec(2)
    method(){}
}
// evaluated 1
// evaluated 2
// executed 2
// executed 1

从外到内进,从内到外执行(离得近的为内)。

封装函数是从外到内的去调用,真实的装饰器是从内到外的去执行的。