ES6常用但被忽略的方法(第十一弹Decorator)

2,872 阅读8分钟

写在开头

  • ES6常用但被忽略的方法 系列文章,整理作者认为一些日常开发可能会用到的一些方法、使用技巧和一些应用场景,细节深入请查看相关内容连接,欢迎补充交流。

相关文章

Decorator

环境配置

  • 由于装饰器目前处于stage 2,所以无法在浏览器中直接使用,我们需要通过babel编译为es5去使用。
  • 我们如果只想简单去使用这样一个语法去做一个了解,我们可以简单配置一下,过程如下:
    1. 全局安装@babel/cli@babel/core
    npm install -g @babel/core @babel/cli
    
    1. 项目目录下初始化一个package.json,并安装decorator的相关babel插件@babel/plugin-proposal-class-properties@babel/plugin-proposal-decorators
    npm init -y // 初始化package.json
    npm install --save-dev @babel/plugin-proposal-class-properties
    npm install --save-dev @babel/plugin-proposal-decorators
    
    1. 在项目根目录下创建.babelrc文件,并添加一下代码。
    {
      "presets": [],
      "plugins": [
        [
          "@babel/plugin-proposal-decorators",
          {
            "legacy": true
          }
        ],
        [
          "@babel/plugin-proposal-class-properties",
          {
            "loose": true
          }
        ]
      ]
    }
    
    1. package.jsonscripts中添加编译命令。
    // package.json
    // babel inputfile -w(实时编译)-o(输出)outputfile
    scripts: {
        build: 'babel es6.js -w -o es5.js'
    }
    
    1. html文件中引入编译后的文件。
    // index.html
    <DOCTYPE html>
    <html>
    ...
    <body>
    ...
    <script src='./es5.js'></script>
    </body>
    </html>
    

介绍

  • Decorator 提案经过了大幅修改,目前还没有定案,不知道语法会不会再变。 装饰器(Decorator)是一种与类(class)相关的语法,用来注释或修改类和类方法,写成@ + 函数名。它可以放在类和类方法的定义前面。
@frozen class Foo {
  @configurable(false)
  @enumerable(true)
  method() {}

  @throttle(500)
  expensiveMethod() {}
}

使用

类的装饰
  • 装饰器可以装饰整个类。装饰器是一个对类进行处理的函数。装饰器函数的第一个参数,就是所要装饰的目标类。
@decorator
class A {}

// 等同于
class A {}
A = decorator(A) || A;
  • 一个参数不够用,可以在装饰器外面再封装一层函数。
function testable(isTestable) {
  return function(target) {
    target.isTestable = isTestable;
  }
}

@testable(true)
class MyTestableClass {}
MyTestableClass.isTestable // true

@testable(false)
class MyClass {}
MyClass.isTestable // false
  • 装饰器对类的行为的改变,是代码编译时发生的,而不是在运行时。这意味着,装饰器能在编译阶段运行代码。也就是说,装饰器本质就是编译时执行的函数。
  • 想添加实例属性,可以通过目标类的prototype对象操作。
function testable(target) {
  target.prototype.isTestable = true;
}

@testable
class MyTestableClass {}

let obj = new MyTestableClass();
obj.isTestable // true
  • 装饰器函数testable是在目标类的prototype对象上添加属性,因此就可以在实例上调用。
方法的装饰
  • 装饰器不仅可以装饰类,还可以装饰类的属性。例如:装饰器readonly用来装饰“类”的getName方法。装饰器函数readonly一共可以接受三个参数,target(装饰的对象)、name(装饰的属性名称),descriptor:属性的描述。
class Person {
  @readonly
  name() { return `${this.first} ${this.last}` }
}
function readonly(target, name, descriptor){
  console.log(target, name, descriptor)
  // descriptor对象原来的值如下
  // {
  //   value: specifiedFunction,
  //   enumerable: false,
  //   configurable: true,
  //   writable: true
  // };
  descriptor.writable = false; // 设置不可写
  return descriptor;
}
// 重新getNameAge不生效
Person.prototype.getName = function(name) {
  console.log(name)
}

const per = new Person()
console.log('getName', per.getName('detanx'))

  • 如果同一个方法有多个装饰器,会像剥洋葱一样,先从外到内进入,然后由内向外执行。
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

为什么装饰器不能用于函数?

  • 装饰器只能用于类和类的方法,不能用于函数,因为存在函数提升。
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

  • core-decorators.js是一个第三方模块,提供了几个常见的装饰器,通过它可以更好地理解装饰器。
@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
@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]
@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"?
}
@deprecate (别名@deprecated)
  • deprecatedeprecated装饰器在控制台显示一条警告,表示该方法将废除。
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.
@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

Mixin

  • 在装饰器的基础上,可以实现Mixin模式。Mixin模式,就是对象继承的一种替代方案,中文译为“混入”(mix in),意为在一个对象之中混入另外一个对象的方法。
  • 部署一个通用脚本mixins.js,将 Mixin 写成一个装饰器。
函数实现
export function mixins(...list) {
  return function (target) {
    Object.assign(target.prototype, ...list);
  };
}
  • 使用mixins这个装饰器,为类“混入”各种方法。
import { mixins } from './mixins';

const Foo = {
  foo() { console.log('foo') }
};

@mixins(Foo)
class MyClass {}

let obj = new MyClass();
obj.foo() // "foo"
类实现
  • 函数写法会改写MyClass类的prototype对象,如果不喜欢这一点,也可以通过类的继承实现 Mixin
class MyClass extends MyBaseClass {
  /* ... */
}
  • MyClass继承了MyBaseClass。如果我们想在MyClass里面“混入”一个foo方法,一个办法是在MyClassMyBaseClass之间插入一个混入类,这个类具有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

  • 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.
  • 上面代码中,TFooTBar都有foo方法,结果traits装饰器报错。
  • 一种解决方法是排除TBarfoo方法。
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方法,混入时就不会报错了。
  • 另一种方法是为TBarfoo方法起一个别名。
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
  • 上面代码为TBarfoo方法起了别名aliasFoo,于是MyClass也可以混入TBarfoo方法了。

  • aliasexcludes方法,可以结合起来使用。

@traits(TBar::excludes('foo','bar')::alias({baz:'tBar'}))
class MyClass {}
  • 上面代码排除了TBarfoo方法和bar方法,为baz方法起了别名tBaz
  • as方法则为上面的代码提供了另一种写法。
@traits(TBar::as({excludes:['foo', 'bar'], alias: {baz: 'exampleBaz'}}))
class MyClass {}