修饰器
Decorator 提案經(jīng)過了大幅修改,目前還沒有定案,不知道語法會不會再變。下面的內(nèi)容完全依據(jù)以前的提案,已經(jīng)有點(diǎn)過時了。等待定案以后,需要完全重寫。
類的修飾
許多面向?qū)ο蟮恼Z言都有修飾器(Decorator)函數(shù),用來修改類的行為。目前,有一個提案將這項功能,引入了 ECMAScript。
@testable class MyTestableClass { // ... } function testable(target) { target.isTestable = true; } MyTestableClass.isTestable // true上面代碼中,@testable就是一個修飾器。它修改了MyTestableClass這個類的行為,為它加上了靜態(tài)屬性isTestable。testable函數(shù)的參數(shù)target是MyTestableClass類本身。
基本上,修飾器的行為就是下面這樣。
@decorator class A {} // 等同于 class A {} A = decorator(A) || A;也就是說,修飾器是一個對類進(jìn)行處理的函數(shù)。修飾器函數(shù)的第一個參數(shù),就是所要修飾的目標(biāo)類。
function testable(target) { // ... }上面代碼中,testable函數(shù)的參數(shù)target,就是會被修飾的類。
如果覺得一個參數(shù)不夠用,可以在修飾器外面再封裝一層函數(shù)。
function testable(isTestable) { return function(target) { target.isTestable = isTestable; } } @testable(true) class MyTestableClass {} MyTestableClass.isTestable // true @testable(false) class MyClass {} MyClass.isTestable // false上面代碼中,修飾器testable可以接受參數(shù),這就等于可以修改修飾器的行為。
注意,修飾器對類的行為的改變,是代碼編譯時發(fā)生的,而不是在運(yùn)行時。這意味著,修飾器能在編譯階段運(yùn)行代碼。也就是說,修飾器本質(zhì)就是編譯時執(zhí)行的函數(shù)。
前面的例子是為類添加一個靜態(tài)屬性,如果想添加實(shí)例屬性,可以通過目標(biāo)類的prototype對象操作。
function testable(target) { target.prototype.isTestable = true; } @testable class MyTestableClass {} let obj = new MyTestableClass(); obj.isTestable // true上面代碼中,修飾器函數(shù)testable是在目標(biāo)類的prototype對象上添加屬性,因此就可以在實(shí)例上調(diào)用。
下面是另外一個例子。
// 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的實(shí)例上面。可以用Object.assign()模擬這個功能。
const Foo = {foo() { console.log('foo') } }; class MyClass {} Object.assign(MyClass.prototype, Foo); let obj = new MyClass(); obj.foo() // 'foo'實(shí)際開發(fā)中,React 與 Redux 庫結(jié)合使用時,常常需要寫成下面這樣。
class MyReactComponent extends React.Component {} export default connect(mapStateToProps, mapDispatchToProps)(MyReactComponent);有了裝飾器,就可以改寫上面的代碼。
@connect(mapStateToProps, mapDispatchToProps) export default class MyReactComponent extends React.Component {}相對來說,后一種寫法看上去更容易理解。
方法的修飾
修飾器不僅可以修飾類,還可以修飾類的屬性。
class Person {@readonlyname() { return `${this.first} ${this.last}` } }上面代碼中,修飾器readonly用來修飾“類”的name方法。
修飾器函數(shù)readonly一共可以接受三個參數(shù)。
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);修飾器第一個參數(shù)是類的原型對象,上例是Person.prototype,修飾器的本意是要“修飾”類的實(shí)例,但是這個時候?qū)嵗€沒生成,所以只能去修飾原型(這不同于類的修飾,那種情況時target參數(shù)指的是類本身);第二個參數(shù)是所要修飾的屬性名,第三個參數(shù)是該屬性的描述對象。
另外,上面代碼說明,修飾器(readonly)會修改屬性的描述對象(descriptor),然后被修改的描述對象再用來定義屬性。
下面是另一個例子,修改屬性描述對象的enumerable屬性,使得該屬性不可遍歷。
class Person {@nonenumerableget kidCount() { return this.children.length; } } function nonenumerable(target, name, descriptor) { descriptor.enumerable = false; return descriptor; }下面的@log修飾器,可以起到輸出日志的作用。
class Math {@logadd(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修飾器的作用就是在執(zhí)行原始的操作之前,執(zhí)行一次console.log,從而達(dá)到輸出日志的目的。
修飾器有注釋的作用。
@testable class Person {@readonly@nonenumerablename() { 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> ); } }如果同一個方法有多個修飾器,會像剝洋蔥一樣,先從外到內(nèi)進(jìn)入,然后由內(nèi)向外執(zhí)行。
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)先進(jìn)入,但是內(nèi)層修飾器@dec(2)先執(zhí)行。
除了注釋,修飾器還能用來類型檢查。所以,對于類來說,這項功能相當(dāng)有用。從長期來看,它將是 JavaScript 代碼靜態(tài)分析的重要工具。
為什么修飾器不能用于函數(shù)?
修飾器只能用于類和類的方法,不能用于函數(shù),因為存在函數(shù)提升。
var counter = 0; var add = function () { counter++; }; @add function foo() { }上面的代碼,意圖是執(zhí)行后counter等于 1,但是實(shí)際上結(jié)果是counter等于 0。因為函數(shù)提升,使得實(shí)際執(zhí)行的代碼是下面這樣。
@add function foo() { } var counter; var add; counter = 0; add = function () { counter++; };下面是另一個例子。
var readOnly = require("some-decorator"); @readOnly function foo() { }上面代碼也有問題,因為實(shí)際執(zhí)行是下面這樣。
var readOnly;@readOnly function foo() { } readOnly = require("some-decorator");總之,由于存在函數(shù)提升,使得修飾器不能用于函數(shù)。類是不會提升的,所以就沒有這方面的問題。
另一方面,如果一定要修飾函數(shù),可以采用高階函數(shù)的形式直接執(zhí)行。
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
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修飾器導(dǎo)致的console.warn()調(diào)用。但是,異步代碼發(fā)出的調(diào)用除外。
import { suppressWarnings } from 'core-decorators'; class Person { @deprecated facepalm() {} @suppressWarnings facepalmWithoutWarning() { this.facepalm(); } } let person = new Person(); person.facepalmWithoutWarning(); // no warning is logged使用修飾器實(shí)現(xiàn)自動發(fā)布事件
我們可以使用修飾器,使得對象的方法被調(diào)用時,自動發(fā)出一個事件。
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('數(shù)據(jù): ', 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,使得原方法被調(diào)用時,會自動發(fā)出一個事件。它使用的事件“發(fā)布/訂閱”庫是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();以后,只要調(diào)用someMethod或者anotherMethod,就會自動發(fā)出一個事件。
$ bash-node index.js 頻道: component 事件: foo.some.message 數(shù)據(jù): { my: 'data' } 頻道: / 事件: foo.some.other 數(shù)據(jù): undefinedMixin
在修飾器的基礎(chǔ)上,可以實(shí)現(xiàn)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類,導(dǎo)致MyClass的實(shí)例obj對象都具有foo方法。這就是“混入”模式的一個簡單實(shí)現(xiàn)。
下面,我們部署一個通用腳本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這個修飾器,實(shí)現(xiàn)了在MyClass類上面“混入”Foo對象的foo方法。
不過,上面的方法會改寫MyClass類的prototype對象,如果不喜歡這一點(diǎn),也可以通過類的繼承實(shí)現(xiàn) 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作為參數(shù),然后返回一個繼承superclass的子類,該子類包含一個foo方法。
接著,目標(biāo)類再去繼承這個混入類,就達(dá)到了“混入”foo方法的目的。
class MyClass extends MyMixin(MyBaseClass) { /* ... */ } let c = new MyClass(); c.foo(); // "foo from MyMixin"如果需要“混入”多個方法,就生成多個混入類。
class MyClass extends Mixin1(Mixin2(MyBaseClass)) { /* ... */ }這種寫法的一個好處,是可以調(diào)用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(); } }上面代碼中,每一次混入發(fā)生時,都調(diào)用了父類的super.foo方法,導(dǎo)致父類的同名方法沒有被覆蓋,行為被保留了下來。
new C().foo() // foo from C // foo from Mixin1 // foo from Mixin2 // foo from STrait
Trait 也是一種修飾器,效果與 Mixin 類似,但是提供更多功能,比如防止同名方法的沖突、排除混入某些方法、為混入的方法起別名等等。
下面采用traits-decorator這個第三方模塊作為例子。這個模塊提供的traits修飾器,不僅可以接受對象,還可以接受 ES6 類作為參數(shù)。
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方法,結(jié)果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上面代碼使用綁定運(yùn)算符(::)在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方法,可以結(jié)合起來使用。
@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 轉(zhuǎn)碼器的支持
目前,Babel 轉(zhuǎn)碼器已經(jīng)支持 Decorator。
首先,安裝@babel/core和@babel/plugin-proposal-decorators。由于后者包括在@babel/preset-stage-0之中,所以改為安裝@babel/preset-stage-0亦可。
$ npm install @babel/core @babel/plugin-proposal-decorators然后,設(shè)置配置文件.babelrc。
{"plugins": ["@babel/plugin-proposal-decorators"] }這時,Babel 就可以對 Decorator 轉(zhuǎn)碼了。
如果要使用 Decorator 的早期規(guī)格,必須將legacy屬性設(shè)為true,默認(rèn)為false。
{"plugins": [ ["@babel/plugin-proposal-decorators", { "legacy": true }] ] }腳本中打開的命令如下。
require("@babel/core").transform("code", { plugins: ["@babel/plugin-proposal-decorators"] });Babel 的官方網(wǎng)站提供一個在線轉(zhuǎn)碼器,只要勾選 Experimental,就能支持 Decorator 的在線轉(zhuǎn)碼。
轉(zhuǎn)載于:https://www.cnblogs.com/miaosj/p/10592316.html
總結(jié)
- 上一篇: 后端系统开发之异常情况处理
- 下一篇: Qt高级——QTestLib单元测试框架