ES6 Decorator 装饰器

Decorator 装饰器

  1. 简介
  • 装饰器(Decorator)是一种与类(class)相关的语法,用来修改类、类方法和类属性。
  • 装饰器是一种函数,写成@ + 函数名。它可以放在类、类方法和类属性的定义前面。
@frozen
class Foo {
  @configurable(false)
  @enumerable(true)
  method() {}

  @throttle(500)
  expensiveMethod() {}
}
  1. 类的装饰
  • 装饰器可以用来装饰整个类。
@testable
class MyTestableClass {
  // ...
}

// target是MyTestableClass类本身。
function testable(target) {
  target.isTestable = true;
}

MyTestableClass.isTestable // true
  • 如果觉得一个参数不够用,可以在装饰器外面再封装一层函数。
function testable(isTestable) {
  return function(target) {
    target.isTestable = isTestable;
  }
}

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

@testable(false)
class MyClass {}
MyClass.isTestable // false
  1. 方法的装饰
  • 装饰器不仅可以装饰类,还可以装饰类的属性。
class Person {
  @readonly
  name() { return `${this.first} ${this.last}` }
}

// target是Person.prototype
function readonly(target, name, descriptor){
  // descriptor对象原来的值如下
  // {
  //   value: 属性值,
  //   enumerable: false, // 是否可遍历
  //   configurable: true, // 是否可配置,即是否可用delete 删除属性或使用Object.defineProperty设置属性
  //   writable: true // 是否可写
  // };
  descriptor.writable = false;
  return descriptor;
}

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

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值