ES6里的修飾器Decorator


  修飾器(Decorator)是一個函數,用來修改類的行為。

一、概述

  ES6 引入了這項功能,目前 Babel 轉碼器已經支持Decorator

  首先,安裝babel-corebabel-plugin-transform-decorators。由於后者包括在babel-preset-stage-0之中,所以改為安裝babel-preset-stage-0亦可

$ npm install babel-core babel-plugin-transform-decorators

  然后,設置配置文件.babelrc

{ "plugins": ["transform-decorators"] }

  這時,Babel就可以對Decorator轉碼了

  腳本中打開的命令如下

babel.transform("code", {plugins: ["transform-decorators"]})

二、類修飾

  下面代碼中,@testable就是一個修飾器。它修改了MyTestableClass這個類的行為,為它加上了靜態屬性isTestable

@testable class MyTestableClass { // ...
} function testable(target) { target.isTestable = true; } MyTestableClass.isTestable // true

  基本上,修飾器的行為就是下面這樣

@decorator class A {} // 等同於

class A {} A = decorator(A) || A;

  修飾器對類的行為的改變,是代碼編譯時發生的,而不是在運行時。這意味着,修飾器能在編譯階段運行代碼,也就是說,修飾器本質就是編譯時執行的函數

1、參數

  修飾器函數的第一個參數,是所要修飾的目標類

function testable(target) { // ...
}

  如果覺得一個參數不夠用,可以在修飾器外面再封裝一層函數

function testable(isTestable) { return function(target) { target.isTestable = isTestable; } } @testable(true) class MyTestableClass {} MyTestableClass.isTestable // true
 @testable(false) class MyClass {} MyClass.isTestable // false

  上面代碼中,修飾器testable可以接受參數,這就等於可以修改修飾器的行為

  前面的例子是為類添加一個靜態屬性,如果想添加實例屬性,可以通過目標類的prototype對象操作

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用來修飾“類”的name方法

1、參數

  此時,修飾器函數一共可以接受三個參數,第一個參數是所要修飾的目標對象,第二個參數是所要修飾的屬性名,第三個參數是該屬性的描述對象

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);

  上面代碼說明,修飾器(readonly)會修改屬性的描述對象(descriptor),然后被修改的描述對象再用來定義屬性。

  下面是另一個例子,修改屬性描述對象的enumerable屬性,使得該屬性不可遍歷

class Person { @nonenumerable get kidCount() { return this.children.length; } } function nonenumerable(target, name, descriptor) { descriptor.enumerable = false; return descriptor; }

2、日志應用

  下面的@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(null, 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方法是只讀和不可枚舉的

3、執行順序

  如果同一個方法有多個修飾器,會像剝洋蔥一樣,先從外到內進入,然后由內向外執行

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)先執行

  除了注釋,修飾器還能用來類型檢查。所以,對於類來說,這項功能相當有用。從長期來看,它將是JS代碼靜態分析的重要工具

四、注意事項

  修飾器只能用於類和類的方法,不能用於函數,因為存在函數提升

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);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM