装饰器(Decorator)
类的修饰
修饰器(Decorator)是一个表达式,用于修改类的行为。这是ES7的一个提案(https://github.com/wycats/javascript-decorators),目前Babel转码器
已经支持。
修饰器对类的行为的改变,是在代码编译时发生的,而不是在运行时。这意味着,修饰器能在编译阶段运行代码。
js
function testable (target) {
target.isTestable = true;
}
@testable
class MyTestableClass {}
console.log(MyTestableClass.isTestable) // true
上面的代码中,@testable
就是一个修饰器。它修改了MyTestableClass
这个类的行为,为它添加了一个静态属性isTestable
。
基本上,修饰器的行为如下:
js
@decorator
class A {}
// 等同于
class A {}
A = decorator(A) || A;
也就是说,修饰器本质上就是能在编译时执行的函数。
修饰器函数可以接受3个参数,依次是目标函数
、属性名
和该属性的描述对象
。后两个参数是可选的。上面的代码中,testable函数
的参数target
就是所要修饰的对象
。如果希望修饰器行为能够根据目标对象的不同而不同,就要在外面再封装一层函数。
js
function testable (isTestable) {
return function (target) {
target.isTestable = isTestable;
}
}
@testable(true)
class MyTestableClass {}
MyTestableClass.isTestable // true
@testable(fasle)
class MyClass {}
MyClass.isTestable // false
上面的代码中,修饰器testable
可以接受参数,这就等于可以修改修饰器的行为。
如果想要为类的实例添加方法,可以在修饰器函数中为目标类的prototype属性
添加方法。
js
function testable (target) {
target.prototype.isTestable = true;
}
@testable
class MyClass {}
let obj = new MyClass();
obj.isTestable // true
下面是另外一个例子:
js
// 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
可以为类添加指定的方法。
修饰器可以用Object.assign()
模拟。
js
const Foo = {
foo () {
console.log('foo');
}
};
class MyClass {}
Object.assign(MyClass.prototype, Foo);
let obj = new MyClass();
obj.foo() // 'foo'
方法的修饰
修饰器不仅可以修饰类,还可以修饰类的属性。
js
class Person {
@readonly
name () {
return `${this.first} ${this.last}`;
}
}
上面的代码中,修饰器readonly
用来修饰“类”的name方法
。
此时,修饰器函数一共可以接受3个参数。目标对象
、所要修饰的属性名
、和该属性的描述对象
。
js
readonly(Person.prototype, 'name', descriptor);
function readonly (target, name, descriptor) {
// descriptor对象原来的值如下
// {
// value: specifiedFunction,
// enumerable: false,
// configurable: true,
// writable: true
// };
descriptor.writable = false;
return descriptor;
}
Object.defineProperty(Person.prototype, 'name', descriptor);
上面的代码说明,修饰器(readonly)会修改属性的描述对象(descriptor),然后被修改的描述对象再用来定义属性。
下面是另一个例子:
js
class Person {
@nonenumerable
get kidCount () { return this.children.length; }
}
function nonenumerable (target, name, descriptor) {
descriptor.enumerable = false;
return descriptor;
}
修饰器有注释的作用。
js
@testable
class Person {
@readonly
@nonenumerable
name () { return `${this.first} ${this.last}`; }
}
从上面的代码中,很明显可以看出name方法
是只读和不可枚举的。
除了注释,修饰器还能用于类型检查。所以,对于类而言,这项功能相当有用。从长期来看,它将是JavaScript代码静态分析的重要工具。
为什么修饰器不能用于函数
修饰器只能用于类和类的方法,不能用于函数,因为存在函数提升。
js
var counter = 0;
var add = function () {
counter++;
}
@add
function foo () {}
上面的代码,本意是执行后counter等于1,但是实际上结果是counter等于0。因为函数提升,使得实际执行的代码如下:
js
var counter;
var add;
@add
function foo () {}
counter = 0;
add = function () {
coutner++;
}
总之,由于存在函数提升,修饰器不能用于函数。类是不会提升的,所以就没有这方面的问题。
core-decorators.js
core-decorators.js
(https://github.com/jayphelps/core-decorators.js)是一个第三方模块,提供了几个常见的修饰器。通过它可以更好地理解修饰器。
@autobind
autobind修饰器
使得方法中的this对象
绑定原始对象。
js
import { autobind } from 'core-decorators';
class Person {
@autobind
getPerson () {
return this;
}
}
let person = new Person();
let getPerson = person.getPerson;
getPerson() === person // true
@readonly
readonly修饰器
使得属性或方法不可写。
js
import { readonly } from 'core-decorators';
class Meal {
@readonly
netree = 'steak';
}
var dinner = new Meal();
dinner.netree = 'salmon';
// Cannot assign to read only property 'entree' of [object object]
@override
override修饰器
检查子类的方法是否正确覆盖了父类的同名方法,如果不正确会报错。
js
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)
}
// 或者
class Child extends Parent {
@override
speaks () {}
// SyntaxError: No descriptor matching Chilad#speak() was found on the prototype chain.
//
// Did you mean "speak"?
}
@deprecate(别名 @deprecated)
deprecate
或deprecated
修饰器在控制台显示一条警告,表示该方法将废除。
js
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.faceplamHard();
// DEPRECATION Person#faceplamHard: We stopped facepalming
person.faceplamHarder();
// DEPRECATION Person#faceplamHarder: We stopped facepalming
//
// See http://knowyourmeme.com/memes/facepalm for more details.
//
@suppressWarnings
suppressWarnings修饰器
抵制decorated修饰器
导致的console.warn()
调用,但异步代码发出的调用除外。
js
import { suppressWarnings } from 'core-decorators';
class Person {
@deprecated
facepalm () {}
@suppressWarnings
facepalmWithoutWarning () {
this.facepalm();
}
}
let person = new Person();
person.facepalmWithoutWarning();
// no warning is logged
使用修饰器实现自动发布事件
我们可以全使用修饰器使得对象的方法被调用时自动发出一个事件。
js
import postal from 'postal/lib/postal.lodash';
export default function publish (topic, channel) {
return function (target, name, descriptor) {
const fn = descriptor.value;
descriptor.value = function () {
let value = fn.apply(this, arguments);
postal.channel(channel || target.channel || '/').publish(topic, value);
};
};
}
上面的代码定义了一个名为pubish
的修饰器,它通过改写descriptor.value
使用原方法被调用时自动发出一个事件。它使用的是事件是“发布/订阅
”库是Postal.js
(https://github.com/postaljs/postal.js)。
它的用法如下:
js
import pubish from 'path/to/descorators/publish';
class FooComponent () {
@publish('foo.some.message', 'component')
someMethod () {
return {
my: 'data'
};
}
@publish('foo.some.other')
anotherMethod () {
// ...
}
}
以后,只要调用someMethod
或anotherMethod
就会自动发出一个事件。
js
let foo = new FooComponent();
foo.someMethod() // 在'component'频道发布'foo.some.message'事件,附带的数据是 { my: 'data' }
foo.anotherMethod() // 在'/'频道发布'foo.some.other'事件,不附带数据
Mixin
在修饰器的基础上可以实现Mixin模式
。所谓Mixin模式
,就是对象继承的一种替代方案,中文译为“混入”(mix in),意为在一个对象中混入另外一个对象的方法。
js
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
写成一个修饰器。
js
export function mixins (...list) {
return function (target) {
Object.assign(target.prototype, ...list);
};
}
然后,就可以使用上面的这个修饰器为类“混入”各种方法。
js
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方法
。
Trait
Trait
也是一种修饰器,效果与Mixin
类似,但是提供更多功能,比如防止同名方法的冲突、排除混入某些方法、为混入的方法起别名等。
下面用traits-decorator
(https://github.com/CocktailJs/traits-decorator)这个第三方模块作为例子。这个模块提供的traits修饰器
不仅可以接受对象,还可以接受ES6类作为参数。
js
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
不允许“混入”同名方法。
js
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方法。
js
import { traits, excludes } from 'traits-decorator'
class TFoo {
foo () { console.log('foo') }
}
const TBar = {
bar () { console.log('bar') },
foo () { console.log('foo') }
}
@traits(TFoo, TBarr::excludes('foo'))
class MyClass {}
let obj = new MyClass();
obj.foo() // 'foo'
obj.bar() // 'bar'
上面的代码使用绑定运算符(::)
在TBar上排除了foo方法,混入时就不会报错了。
另一种方法是为TBar的foo方法起一个别名。
js
import { traits, alias } from 'traits-decorator'
class TFoo {
foo () { console.log('foo') }
}
const TBar = {
bar () { console.log('bar') },
foo () { console.log('foo') }
}
@traits(TFoo, TBarr::alias({foo: 'aliasFoo'}))
class MyClass {}
let obj = new MyClass();
obj.foo() // 'foo'
obj.aliasFoo() // 'foo'
obj.bar() // 'bar'
alias
和excludes
方法可以结合起来使用。
js
@traits(TExample::excludes('foo', 'bar')::alias({baz: 'exampleBaz'}))
class MyClass {}
as方法
则为上面的代码提供了另一种写法。
js
@traits(TExample::as({excludes: ['foo', 'bar'], alias: {baz: 'exampleBaz'}}))
class MyClass {}
Babel转码器的支持
目前,Babel转码器已经支持Decorator
。
首先,安装babel-core
和babel-plugin-transform-decorators
。由于后者包括在babel-preset-stage-0
之中,所以改为安装babel-preset-stage-0
亦可。
shell
$ npm i babel-core babel-plugin-transform-decorators
然后,设置配置文件.babelrc
。
babelrc
{
"plugins": ["transform-decorators"]
}
这时,Babel
就可以对Decorator
转码了。
脚本中打开的命令如下。
js
babel.transform("code", {plugins: ["transform-decorators"]})
Babel
的官方网站提供一个在线转码器(https://babeljs.io/repl),只要勾选Experimental
,就能支持Decorator
的在线转码。
以上,摘抄自阮一峰老师的《ES6标准入门》