ES7装饰器 Decorator

装饰器是ES2016 stage-2的一个草案,但是在babel的支持下,已被广泛使用。关于ES规范可参考Github:tc39/proposals

类的修饰

@testable
class MyTestableClass {
  // ...
}

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

MyTestableClass.isTestable // true

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

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

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

@testable
class MyTestableClass {}

let obj = new MyTestableClass();
obj.isTestable // true

方法的修饰

多了两个参数(类的没有)

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;
}

又例如一个日志的修饰器

class Math {
  @log
  add(a, b) {
    return a + b;
  }
}

function log(target, name, descriptor) {
  var oldValue = descriptor.value;

  descriptor.value = function(...list) {
    console.log(list);
    console.log(`Calling ${name} with`, ...list);
    return oldValue.call(this, ...list);
  };

  return descriptor;
}

const math = new Math();

// passed parameters should get logged now
let result = math.add(2, 4);

console.log(result)

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

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

❗️注意如果有多个装饰器修改了getter和setter,那么叠加使用会存在问题,因为后面的会覆盖前面的getter和setter

为什么修饰器不能用于函数

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

常用的第三方装饰器库

core-decorators.js是一个第三方模块,提供了几个常见的修饰器,通过它可以更好地理解修饰器。
提供了 @autobind @readonly @override @deprecate 等方法。

Trait 也是一种修饰器,效果与 Mixin 类似,但是提供更多功能,比如防止同名方法的冲突、排除混入某些方法、为混入的方法起别名等等。
例如traits-decorator。这个模块提供的traits修饰器,不仅可以接受对象,还可以接受 ES6 类作为参数。

参考链接:
阮一峰的ES6教程
Decorator 的详细介绍
JS 装饰器(Decorator)场景实战

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 类的修饰 许多面向对象的语言都有装饰器(Decorator)函数,用来修改类的行为。目前,有一个提案将这项功能,引...
    天魂_TH阅读 611评论 0 2
  • python装饰器是在函数调用之上的修饰,这些修饰是在声明或者定义一个函数的时候进行设置的。同时,装饰器是一个返回...
    happy_19阅读 661评论 0 5
  • 装饰器语法是Python中一个很重要的语法,刚学Python时就有接触,但当时理解起来很困难,不过最近这一次学习装...
    _kkk阅读 375评论 0 2
  • 前言 许多面向对象都有decorator(装饰器)函数,比如python中也可以用decorator函数来强化代码...
    ITgecko阅读 8,340评论 0 0
  • 许家成的J715V车子接回来,他让我们先给他买保险审车处理违章,开始不知道他是跟谁联系的,接车的时候也没给客户说要...
    捌柒玖零阅读 142评论 0 0