ES6知识点整理之----Decorator(修饰器)

类的修饰


修饰器是一个对类进行处理的函数。修饰器函数的第一个参数,就是所要修饰的目标类。
修饰器的行为:
@decorator
class A {}

// 等同于

class A {}
A = decorator(A) || A;

@testable:修改了类的行为,为它加上了静态属性isTestableisTestable
@testable
class MyTestableClass {
  // ...
}

//target是MyTestableClass类自己
function testable(target) {
  target.isTestable = true;
}

MyTestableClass.isTestable // true

若是以为一个参数不够用,能够在修饰器外面再封装一层函数。javascript

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

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

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

若是想添加实例属性,能够经过目标类的prototype对象操做。java

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

修饰器函数readonly一共能够接受三个参数:app

  • 第一个参数是类的原型对象
  • 第二个参数是所要修饰的属性名
  • 第三个参数是该属性的描述对象

@log修饰器,能够起到输出日志的做用。函数

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

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

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

  return descriptor;
}

const math = new Math();

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

修饰器有注释的做用。测试

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

//Person类是可测试的,而name方法是只读和不可枚举的。
修饰器只能用于类和类的方法,不能用于函数,由于存在函数提高。

core-decorators.js(略)

是一个第三方模块,提供了几个常见的修饰器,经过它能够更好地理解修饰器。this

 

使用修饰器实现自动发布事件(略)

Mixin模式(略)

Trait(略)

Trait 也是一种修饰器,效果与 Mixin 相似,可是提供更多功能spa

Babel 转码器的支持(略)

目前,Babel 转码器已经支持 Decorator。
相关文章
相关标签/搜索