修饰器是一个对类进行处理的函数。修饰器函数的第一个参数,就是所要修饰的目标类。
修饰器的行为:
@decorator class A {} // 等同于 class A {} A = decorator(A) || A;
@testable:修改了类的行为,为它加上了静态属性isTestable
isTestable
@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方法是只读和不可枚举的。
修饰器只能用于类和类的方法,不能用于函数,由于存在函数提高。
是一个第三方模块,提供了几个常见的修饰器,经过它能够更好地理解修饰器。this
模式(略)Trait 也是一种修饰器,效果与 Mixin 相似,可是提供更多功能spa
目前,Babel 转码器已经支持 Decorator。