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 的在線轉碼。