Will's blog Will's blog
首页
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《JavaScript教程》
    • 《JavaScript高级程序设计》
    • 《ES6 教程》
    • 《Vue》
    • 《React》
    • 《TypeScript 从零实现 axios》
    • 《Git》
    • TypeScript
    • JS设计模式总结
  • HTML
  • CSS
  • VUE
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

will

前端小学生
首页
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《JavaScript教程》
    • 《JavaScript高级程序设计》
    • 《ES6 教程》
    • 《Vue》
    • 《React》
    • 《TypeScript 从零实现 axios》
    • 《Git》
    • TypeScript
    • JS设计模式总结
  • HTML
  • CSS
  • VUE
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • ECMAScript 6 简介
  • let 和 const 命令
  • 变量的解构赋值
  • 字符串的扩展
  • 字符串的新增方法
  • 正则的扩展
  • 数值的扩展
  • 函数的扩展
  • 数组的扩展
  • 对象的扩展
  • 对象的新增方法
  • Symbol
  • Set 和 Map 数据结构
  • Proxy
  • Reflect
  • Promise 对象
  • Iterator 和 for-of 循环
  • Generator 函数的语法
  • Generator 函数的异步应用
  • async 函数
  • Class 的基本语法
  • Class 的继承
  • Module 的语法
  • Module 的加载实现
  • 编程风格
  • 读懂 ECMAScript 规格
  • 异步遍历器
  • ArrayBuffer
  • 最新提案
  • 装饰器
    • 类的装饰
    • 方法的装饰
    • 为什么装饰器不能用于函数?
    • core-decorators.js
    • 使用装饰器实现自动发布事件
    • Mixin
    • Trait
  • 函数式编程
  • Mixin
  • SIMD
  • 参考链接
  • 《ES6 教程》笔记
阮一峰
2020-02-09
目录

装饰器

# 装饰器

[说明] Decorator 提案经过了大幅修改,目前还没有定案,不知道语法会不会再变。下面的内容完全依据以前的提案,已经有点过时了。等待定案以后,需要完全重写。

装饰器(Decorator)是一种与类(class)相关的语法,用来注释或修改类和类方法。许多面向对象的语言都有这项功能,目前有一个提案 (opens new window)将其引入了 ECMAScript。 装饰器是一种函数,写成@ + 函数名。它可以放在类和类方法的定义前面。

@frozen class Foo {

  @configurable(false)

  @enumerable(true)

  method() {}



  @throttle(500)

  expensiveMethod() {}

}

1
2
3
4
5
6
7
8

上面代码一共使用了四个装饰器,一个用在类本身,另外三个用在类方法。它们不仅增加了代码的可读性,清晰地表达了意图,而且提供一种方便的手段,增加或修改类的功能。

# 类的装饰

装饰器可以用来装饰整个类。

@testable

class MyTestableClass {

  // ...

}



function testable(target) {

  target.isTestable = true;

}



MyTestableClass.isTestable // true

1
2
3
4
5
6
7
8
9
10

上面代码中,@testable就是一个装饰器。它修改了MyTestableClass这个类的行为,为它加上了静态属性isTestable。testable函数的参数target是MyTestableClass类本身。

基本上,装饰器的行为就是下面这样。

@decorator

class A {}



// 等同于



class A {}

A = decorator(A) || A;

1
2
3
4
5
6
7

也就是说,装饰器是一个对类进行处理的函数。装饰器函数的第一个参数,就是所要装饰的目标类。

function testable(target) {

  // ...

}

1
2
3

上面代码中,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

1
2
3
4
5
6
7
8
9
10
11
12
13

上面代码中,装饰器testable可以接受参数,这就等于可以修改装饰器的行为。

注意,装饰器对类的行为的改变,是代码编译时发生的,而不是在运行时。这意味着,装饰器能在编译阶段运行代码。也就是说,装饰器本质就是编译时执行的函数。

前面的例子是为类添加一个静态属性,如果想添加实例属性,可以通过目标类的prototype对象操作。

function testable(target) {

  target.prototype.isTestable = true;

}



@testable

class MyTestableClass {}



let obj = new MyTestableClass();

obj.isTestable // true

1
2
3
4
5
6
7
8
9

上面代码中,装饰器函数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'

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

上面代码通过装饰器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'

1
2
3
4
5
6
7
8
9
10

实际开发中,React 与 Redux 库结合使用时,常常需要写成下面这样。

class MyReactComponent extends React.Component {}



export default connect(mapStateToProps, mapDispatchToProps)(MyReactComponent);

1
2
3

有了装饰器,就可以改写上面的代码。

@connect(mapStateToProps, mapDispatchToProps)

export default class MyReactComponent extends React.Component {}

1
2

相对来说,后一种写法看上去更容易理解。

# 方法的装饰

装饰器不仅可以装饰类,还可以装饰类的属性。

class Person {

  @readonly

  name() { return `${this.first} ${this.last}` }

}

1
2
3
4

上面代码中,装饰器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);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

装饰器第一个参数是类的原型对象,上例是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;

}

1
2
3
4
5
6
7
8
9

下面的@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);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

上面代码中,@log装饰器的作用就是在执行原始的操作之前,执行一次console.log,从而达到输出日志的目的。

装饰器有注释的作用。

@testable

class Person {

  @readonly

  @nonenumerable

  name() { return `${this.first} ${this.last}` }

}

1
2
3
4
5
6

从上面代码中,我们一眼就能看出,Person类是可测试的,而name方法是只读和不可枚举的。

下面是使用 Decorator 写法的组件 (opens new window),看上去一目了然。

@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>

    );

  }

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

如果同一个方法有多个装饰器,会像剥洋葱一样,先从外到内进入,然后由内向外执行。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14

上面代码中,外层装饰器@dec(1)先进入,但是内层装饰器@dec(2)先执行。

除了注释,装饰器还能用来类型检查。所以,对于类来说,这项功能相当有用。从长期来看,它将是 JavaScript 代码静态分析的重要工具。

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

装饰器只能用于类和类的方法,不能用于函数,因为存在函数提升。

var counter = 0;



var add = function () {

  counter++;

};



@add

function foo() {

}

1
2
3
4
5
6
7
8
9

上面的代码,意图是执行后counter等于 1,但是实际上结果是counter等于 0。因为函数提升,使得实际执行的代码是下面这样。

@add

function foo() {

}



var counter;

var add;



counter = 0;



add = function () {

  counter++;

};

1
2
3
4
5
6
7
8
9
10
11
12

下面是另一个例子。

var readOnly = require("some-decorator");



@readOnly

function foo() {

}

1
2
3
4
5

上面代码也有问题,因为实际执行是下面这样。

var readOnly;



@readOnly

function foo() {

}



readOnly = require("some-decorator");

1
2
3
4
5
6
7

总之,由于存在函数提升,使得装饰器不能用于函数。类是不会提升的,所以就没有这方面的问题。

另一方面,如果一定要装饰函数,可以采用高阶函数的形式直接执行。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14

# core-decorators.js

core-decorators.js (opens new window)是一个第三方模块,提供了几个常见的装饰器,通过它可以更好地理解装饰器。

(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

1
2
3
4
5
6
7
8
9
10
11
12
13
14

(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]

1
2
3
4
5
6
7
8
9
10

(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"?

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

(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.

//

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

(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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 使用装饰器实现自动发布事件

我们可以使用装饰器,使得对象的方法被调用时,自动发出一个事件。

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

    };

  };

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

上面代码定义了一个名为publish的装饰器,它通过改写descriptor.value,使得原方法被调用时,会自动发出一个事件。它使用的事件“发布/订阅”库是Postal.js (opens new window)。

它的用法如下。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

以后,只要调用someMethod或者anotherMethod,就会自动发出一个事件。

$ bash-node index.js

频道:  component

事件:  foo.some.message

数据:  { my: 'data' }



频道:  /

事件:  foo.some.other

数据:  undefined

1
2
3
4
5
6
7
8

# Mixin

在装饰器的基础上,可以实现Mixin模式。所谓Mixin模式,就是对象继承的一种替代方案,中文译为“混入”(mix in),意为在一个对象之中混入另外一个对象的方法。

请看下面的例子。

const Foo = {

  foo() { console.log('foo') }

};



class MyClass {}



Object.assign(MyClass.prototype, Foo);



let obj = new MyClass();

obj.foo() // 'foo'

1
2
3
4
5
6
7
8
9
10

上面代码之中,对象Foo有一个foo方法,通过Object.assign方法,可以将foo方法“混入”MyClass类,导致MyClass的实例obj对象都具有foo方法。这就是“混入”模式的一个简单实现。

下面,我们部署一个通用脚本mixins.js,将 Mixin 写成一个装饰器。

export function mixins(...list) {

  return function (target) {

    Object.assign(target.prototype, ...list);

  };

}

1
2
3
4
5

然后,就可以使用上面这个装饰器,为类“混入”各种方法。

import { mixins } from './mixins';



const Foo = {

  foo() { console.log('foo') }

};



@mixins(Foo)

class MyClass {}



let obj = new MyClass();

obj.foo() // "foo"

1
2
3
4
5
6
7
8
9
10
11

通过mixins这个装饰器,实现了在MyClass类上面“混入”Foo对象的foo方法。

不过,上面的方法会改写MyClass类的prototype对象,如果不喜欢这一点,也可以通过类的继承实现 Mixin。

class MyClass extends MyBaseClass {

  /* ... */

}

1
2
3

上面代码中,MyClass继承了MyBaseClass。如果我们想在MyClass里面“混入”一个foo方法,一个办法是在MyClass和MyBaseClass之间插入一个混入类,这个类具有foo方法,并且继承了MyBaseClass的所有方法,然后MyClass再继承这个类。

let MyMixin = (superclass) => class extends superclass {

  foo() {

    console.log('foo from MyMixin');

  }

};

1
2
3
4
5

上面代码中,MyMixin是一个混入类生成器,接受superclass作为参数,然后返回一个继承superclass的子类,该子类包含一个foo方法。

接着,目标类再去继承这个混入类,就达到了“混入”foo方法的目的。

class MyClass extends MyMixin(MyBaseClass) {

  /* ... */

}



let c = new MyClass();

c.foo(); // "foo from MyMixin"

1
2
3
4
5
6

如果需要“混入”多个方法,就生成多个混入类。

class MyClass extends Mixin1(Mixin2(MyBaseClass)) {

  /* ... */

}

1
2
3

这种写法的一个好处,是可以调用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();

  }

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

上面代码中,每一次混入发生时,都调用了父类的super.foo方法,导致父类的同名方法没有被覆盖,行为被保留了下来。

new C().foo()

// foo from C

// foo from Mixin1

// foo from Mixin2

// foo from S

1
2
3
4
5

# Trait

Trait 也是一种装饰器,效果与 Mixin 类似,但是提供更多功能,比如防止同名方法的冲突、排除混入某些方法、为混入的方法起别名等等。

下面采用traits-decorator (opens new window)这个第三方模块作为例子。这个模块提供的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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

上面代码中,通过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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

上面代码中,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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

上面代码使用绑定运算符(::)在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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

上面代码为TBar的foo方法起了别名aliasFoo,于是MyClass也可以混入TBar的foo方法了。

alias和excludes方法,可以结合起来使用。

@traits(TExample::excludes('foo','bar')::alias({baz:'exampleBaz'}))

class MyClass {}

1
2

上面代码排除了TExample的foo方法和bar方法,为baz方法起了别名exampleBaz。

as方法则为上面的代码提供了另一种写法。

@traits(TExample::as({excludes:['foo', 'bar'], alias: {baz: 'exampleBaz'}}))

class MyClass {}

1
2
编辑此页 (opens new window)
#ES6
上次更新: 2024/08/22, 14:42:43
最新提案
函数式编程

← 最新提案 函数式编程→

最近更新
01
我用AI写前端代码这一年:从怀疑到真香的转变
09-15
02
基于 Next.js 的无人机数据孪生可视化平台实践
07-17
03
vite 包缓存问题 处理
06-04
更多文章>
Theme by Vdoing | Copyright © 2019-2025 Will | MIT License | 桂ICP备2024034950号 | 桂公网安备45142202000030
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式