Decorator 提案通过了大幅修改,目前尚未定案,不知道语法会不会再变。下面的内容彻底依据之前的提案,已经有点过期了。等待定案之后,须要彻底重写。javascript
许多面向对象的语言都有修饰器(Decorator)函数,用来修改类的行为。目前,有一个提案将这项功能,引入了 ECMAScript。css
@testable
class MyTestableClass { // ... } function testable(target) { target.isTestable = true; } MyTestableClass.isTestable // true
上面代码中,@testable
就是一个修饰器。它修改了MyTestableClass
这个类的行为,为它加上了静态属性isTestable
。testable
函数的参数target
是MyTestableClass
类自己。java
基本上,修饰器的行为就是下面这样。node
@decorator
class A {} // 等同于 class A {} A = decorator(A) || A;
也就是说,修饰器是一个对类进行处理的函数。修饰器函数的第一个参数,就是所要修饰的目标类。git
function testable(target) { // ... }
上面代码中,testable
函数的参数target
,就是会被修饰的类。github
若是以为一个参数不够用,能够在修饰器外面再封装一层函数。npm
function testable(isTestable) { return function(target) { target.isTestable = isTestable; } } @testable(true) class MyTestableClass {} MyTestableClass.isTestable // true @testable(false) class MyClass {} MyClass.isTestable // false
上面代码中,修饰器testable
能够接受参数,这就等于能够修改修饰器的行为。bash
注意,修饰器对类的行为的改变,是代码编译时发生的,而不是在运行时。这意味着,修饰器能在编译阶段运行代码。也就是说,修饰器本质就是编译时执行的函数。babel
前面的例子是为类添加一个静态属性,若是想添加实例属性,能够经过目标类的prototype
对象操做。app
function testable(target) { target.prototype.isTestable = true; } @testable class MyTestableClass {} let obj = new MyTestableClass(); obj.isTestable // true
上面代码中,修饰器函数testable
是在目标类的prototype
对象上添加属性,所以就能够在实例上调用。
下面是另一个例子。
// mixins.js export function mixins(...list) { return function (target) { Object.assign(target.prototype, ...list) } } // main.js import { mixins } from './mixins' const Foo = { foo() { console.log('foo') } }; @mixins(Foo) class MyClass {} let obj = new MyClass(); obj.foo() // 'foo'
上面代码经过修饰器mixins
,把Foo
对象的方法添加到了MyClass
的实例上面。能够用Object.assign()
模拟这个功能。
const Foo = { foo() { console.log('foo') } }; class MyClass {} Object.assign(MyClass.prototype, Foo); let obj = new MyClass(); obj.foo() // 'foo'
实际开发中,React 与 Redux 库结合使用时,经常须要写成下面这样。
class MyReactComponent extends React.Component {} export default connect(mapStateToProps, mapDispatchToProps)(MyReactComponent);
有了装饰器,就能够改写上面的代码。
@connect(mapStateToProps, mapDispatchToProps) export default class MyReactComponent extends React.Component {}
相对来讲,后一种写法看上去更容易理解。
修饰器不只能够修饰类,还能够修饰类的属性。
class Person { @readonly name() { return `${this.first} ${this.last}` } }
上面代码中,修饰器readonly
用来修饰“类”的name
方法。
修饰器函数readonly
一共能够接受三个参数。
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);
修饰器第一个参数是类的原型对象,上例是Person.prototype
,修饰器的本意是要“修饰”类的实例,可是这个时候实例还没生成,因此只能去修饰原型(这不一样于类的修饰,那种状况时target
参数指的是类自己);第二个参数是所要修饰的属性名,第三个参数是该属性的描述对象。
另外,上面代码说明,修饰器(readonly)会修改属性的描述对象(descriptor),而后被修改的描述对象再用来定义属性。
下面是另外一个例子,修改属性描述对象的enumerable
属性,使得该属性不可遍历。
class Person { @nonenumerable get kidCount() { return this.children.length; } } function nonenumerable(target, name, descriptor) { descriptor.enumerable = false; return descriptor; }
下面的@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);
上面代码中,@log
修饰器的做用就是在执行原始的操做以前,执行一次console.log
,从而达到输出日志的目的。
修饰器有注释的做用。
@testable
class Person { @readonly @nonenumerable name() { return `${this.first} ${this.last}` } }
从上面代码中,咱们一眼就能看出,Person
类是可测试的,而name
方法是只读和不可枚举的。
下面是使用 Decorator 写法的组件,看上去一目了然。
@Component({ tag: 'my-component', styleUrl: 'my-component.scss' }) export class MyComponent { @Prop() first: string; @Prop() last: string; @State() isVisible: boolean = true; render() { return ( <p>Hello, my name is {this.first} {this.last}</p> ); } }
若是同一个方法有多个修饰器,会像剥洋葱同样,先从外到内进入,而后由内向外执行。
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
上面代码中,外层修饰器@dec(1)
先进入,可是内层修饰器@dec(2)
先执行。
除了注释,修饰器还能用来类型检查。因此,对于类来讲,这项功能至关有用。从长期来看,它将是 JavaScript 代码静态分析的重要工具。
修饰器只能用于类和类的方法,不能用于函数,由于存在函数提高。
var counter = 0; var add = function () { counter++; }; @add function foo() { }
上面的代码,意图是执行后counter
等于 1,可是实际上结果是counter
等于 0。由于函数提高,使得实际执行的代码是下面这样。
@add
function foo() { } var counter; var add; counter = 0; add = function () { counter++; };
下面是另外一个例子。
var readOnly = require("some-decorator"); @readOnly function foo() { }
上面代码也有问题,由于实际执行是下面这样。
var readOnly; @readOnly function foo() { } readOnly = require("some-decorator");
总之,因为存在函数提高,使得修饰器不能用于函数。类是不会提高的,因此就没有这方面的问题。
另外一方面,若是必定要修饰函数,能够采用高阶函数的形式直接执行。
function doSomething(name) { console.log('Hello, ' + name); } function loggingDecorator(wrapped) { return function() { console.log('Starting'); const result = wrapped.apply(this, arguments); console.log('Finished'); return result; } } const wrapped = loggingDecorator(doSomething);
core-decorators.js是一个第三方模块,提供了几个常见的修饰器,经过它能够更好地理解修饰器。
(1)@autobind
autobind
修饰器使得方法中的this
对象,绑定原始对象。
import { autobind } from 'core-decorators'; class Person { @autobind getPerson() { return this; } } let person = new Person(); let getPerson = person.getPerson; getPerson() === person; // true
(2)@readonly
readonly
修饰器使得属性或方法不可写。
import { readonly } from 'core-decorators'; class Meal { @readonly entree = 'steak'; } var dinner = new Meal(); dinner.entree = 'salmon'; // Cannot assign to read only property 'entree' of [object Object]
(3)@override
override
修饰器检查子类的方法,是否正确覆盖了父类的同名方法,若是不正确会报错。
import { override } from 'core-decorators'; class Parent { speak(first, second) {} } class Child extends Parent { @override speak() {} // SyntaxError: Child#speak() does not properly override Parent#speak(first, second) } // or class Child extends Parent { @override speaks() {} // SyntaxError: No descriptor matching Child#speaks() was found on the prototype chain. // // Did you mean "speak"? }
(4)@deprecate (别名@deprecated)
deprecate
或deprecated
修饰器在控制台显示一条警告,表示该方法将废除。
import { deprecate } from 'core-decorators'; class Person { @deprecate facepalm() {} @deprecate('We stopped facepalming') facepalmHard() {} @deprecate('We stopped facepalming', { url: 'http://knowyourmeme.com/memes/facepalm' }) facepalmHarder() {} } let person = new Person(); person.facepalm(); // DEPRECATION Person#facepalm: This function will be removed in future versions. person.facepalmHard(); // DEPRECATION Person#facepalmHard: We stopped facepalming person.facepalmHarder(); // DEPRECATION Person#facepalmHarder: We stopped facepalming // // See http://knowyourmeme.com/memes/facepalm for more details. //
(5)@suppressWarnings
suppressWarnings
修饰器抑制deprecated
修饰器致使的console.warn()
调用。可是,异步代码发出的调用除外。
import { suppressWarnings } from 'core-decorators'; class Person { @deprecated facepalm() {} @suppressWarnings facepalmWithoutWarning() { this.facepalm(); } } let person = new Person(); person.facepalmWithoutWarning(); // no warning is logged
咱们可使用修饰器,使得对象的方法被调用时,自动发出一个事件。
const postal = require("postal/lib/postal.lodash"); export default function publish(topic, channel) { const channelName = channel || '/'; const msgChannel = postal.channel(channelName); msgChannel.subscribe(topic, v => { console.log('频道: ', channelName); console.log('事件: ', topic); console.log('数据: ', v); }); return function(target, name, descriptor) { const fn = descriptor.value; descriptor.value = function() { let value = fn.apply(this, arguments); msgChannel.publish(topic, value); }; }; }
上面代码定义了一个名为publish
的修饰器,它经过改写descriptor.value
,使得原方法被调用时,会自动发出一个事件。它使用的事件“发布/订阅”库是Postal.js。
它的用法以下。
// index.js import publish from './publish'; class FooComponent { @publish('foo.some.message', 'component') someMethod() { return { my: 'data' }; } @publish('foo.some.other') anotherMethod() { // ... } } let foo = new FooComponent(); foo.someMethod(); foo.anotherMethod();
之后,只要调用someMethod
或者anotherMethod
,就会自动发出一个事件。
$ bash-node index.js 频道: component 事件: foo.some.message 数据: { my: 'data' } 频道: / 事件: foo.some.other 数据: undefined
在修饰器的基础上,能够实现Mixin
模式。所谓Mixin
模式,就是对象继承的一种替代方案,中文译为“混入”(mix in),意为在一个对象之中混入另一个对象的方法。
请看下面的例子。
const Foo = { foo() { console.log('foo') } }; class MyClass {} Object.assign(MyClass.prototype, Foo); let obj = new MyClass(); obj.foo() // 'foo'
上面代码之中,对象Foo
有一个foo
方法,经过Object.assign
方法,能够将foo
方法“混入”MyClass
类,致使MyClass
的实例obj
对象都具备foo
方法。这就是“混入”模式的一个简单实现。
下面,咱们部署一个通用脚本mixins.js
,将 Mixin 写成一个修饰器。
export function mixins(...list) { return function (target) { Object.assign(target.prototype, ...list); }; }
而后,就可使用上面这个修饰器,为类“混入”各类方法。
import { mixins } from './mixins'; const Foo = { foo() { console.log('foo') } }; @mixins(Foo) class MyClass {} let obj = new MyClass(); obj.foo() // "foo"
经过mixins
这个修饰器,实现了在MyClass
类上面“混入”Foo
对象的foo
方法。
不过,上面的方法会改写MyClass
类的prototype
对象,若是不喜欢这一点,也能够经过类的继承实现 Mixin。
class MyClass extends MyBaseClass { /* ... */ }
上面代码中,MyClass
继承了MyBaseClass
。若是咱们想在MyClass
里面“混入”一个foo
方法,一个办法是在MyClass
和MyBaseClass
之间插入一个混入类,这个类具备foo
方法,而且继承了MyBaseClass
的全部方法,而后MyClass
再继承这个类。
let MyMixin = (superclass) => class extends superclass { foo() { console.log('foo from MyMixin'); } };
上面代码中,MyMixin
是一个混入类生成器,接受superclass
做为参数,而后返回一个继承superclass
的子类,该子类包含一个foo
方法。
接着,目标类再去继承这个混入类,就达到了“混入”foo
方法的目的。
class MyClass extends MyMixin(MyBaseClass) { /* ... */ } let c = new MyClass(); c.foo(); // "foo from MyMixin"
若是须要“混入”多个方法,就生成多个混入类。
class MyClass extends Mixin1(Mixin2(MyBaseClass)) { /* ... */ }
这种写法的一个好处,是能够调用super
,所以能够避免在“混入”过程当中覆盖父类的同名方法。
let Mixin1 = (superclass) => class extends superclass { foo() { console.log('foo from Mixin1'); if (super.foo) super.foo(); } }; let Mixin2 = (superclass) => class extends superclass { foo() { console.log('foo from Mixin2'); if (super.foo) super.foo(); } }; class S { foo() { console.log('foo from S'); } } class C extends Mixin1(Mixin2(S)) { foo() { console.log('foo from C'); super.foo(); } }
上面代码中,每一次混入
发生时,都调用了父类的super.foo
方法,致使父类的同名方法没有被覆盖,行为被保留了下来。
new C().foo() // foo from C // foo from Mixin1 // foo from Mixin2 // foo from S
Trait 也是一种修饰器,效果与 Mixin 相似,可是提供更多功能,好比防止同名方法的冲突、排除混入某些方法、为混入的方法起别名等等。
下面采用traits-decorator这个第三方模块做为例子。这个模块提供的traits
修饰器,不只能够接受对象,还能够接受 ES6 类做为参数。
import { traits } from 'traits-decorator'; class TFoo { foo() { console.log('foo') } } const TBar = { bar() { console.log('bar') } }; @traits(TFoo, TBar) class MyClass { } let obj = new MyClass(); obj.foo() // foo obj.bar() // bar
上面代码中,经过traits
修饰器,在MyClass
类上面“混入”了TFoo
类的foo
方法和TBar
对象的bar
方法。
Trait 不容许“混入”同名方法。
import { traits } from 'traits-decorator'; class TFoo { foo() { console.log('foo') } } const TBar = { bar() { console.log('bar') }, foo() { console.log('foo') } }; @traits(TFoo, TBar) class MyClass { } // 报错 // throw new Error('Method named: ' + methodName + ' is defined twice.'); // ^ // Error: Method named: foo is defined twice.
上面代码中,TFoo
和TBar
都有foo
方法,结果traits
修饰器报错。
一种解决方法是排除TBar
的foo
方法。
import { traits, excludes } from 'traits-decorator'; class TFoo { foo() { console.log('foo') } } const TBar = { bar() { console.log('bar') }, foo() { console.log('foo') } }; @traits(TFoo, TBar::excludes('foo')) class MyClass { } let obj = new MyClass(); obj.foo() // foo obj.bar() // bar
上面代码使用绑定运算符(::)在TBar
上排除foo
方法,混入时就不会报错了。
另外一种方法是为TBar
的foo
方法起一个别名。
import { traits, alias } from 'traits-decorator'; class TFoo { foo() { console.log('foo') } } const TBar = { bar() { console.log('bar') }, foo() { console.log('foo') } }; @traits(TFoo, TBar::alias({foo: 'aliasFoo'})) class MyClass { } let obj = new MyClass(); obj.foo() // foo obj.aliasFoo() // foo obj.bar() // bar
上面代码为TBar
的foo
方法起了别名aliasFoo
,因而MyClass
也能够混入TBar
的foo
方法了。
alias
和excludes
方法,能够结合起来使用。
@traits(TExample::excludes('foo','bar')::alias({baz:'exampleBaz'})) class MyClass {}
上面代码排除了TExample
的foo
方法和bar
方法,为baz
方法起了别名exampleBaz
。
as
方法则为上面的代码提供了另外一种写法。
@traits(TExample::as({excludes:['foo', 'bar'], alias: {baz: 'exampleBaz'}})) class MyClass {}
目前,Babel 转码器已经支持 Decorator。
首先,安装@babel/core
和@babel/plugin-proposal-decorators
。因为后者包括在@babel/preset-stage-0
之中,因此改成安装@babel/preset-stage-0
亦可。
$ npm install @babel/core @babel/plugin-proposal-decorators
而后,设置配置文件.babelrc
。
{ "plugins": ["@babel/plugin-proposal-decorators"] }
这时,Babel 就能够对 Decorator 转码了。
若是要使用 Decorator 的早期规格,必须将legacy
属性设为true
,默认为false
。
{ "plugins": [ ["@babel/plugin-proposal-decorators", { "legacy": true }] ] }
脚本中打开的命令以下。
require("@babel/core").transform("code", { plugins: ["@babel/plugin-proposal-decorators"] });
Babel 的官方网站提供一个在线转码器,只要勾选 Experimental,就能支持 Decorator 的在线转码。