ES6学习13(修饰器)

类的修饰

修饰器(Decorator)是一个函数,用来修改类的行为。这是ES7的一个提案,目前Babel转码器已经支持。

修饰器对类的行为的改变,是代码编译时发生的,而不是在运行时。这意味着,修饰器能在编译阶段运行代码。

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

基本上,修饰器的行为就是下面这样:

@decorator
class A {}
// 等同于
class A {}
A = decorator(A) || A;

上面的例子使用babel转码后得到的ES5代码如下:

"use strict";
var _class;
function _classCallCheck(instance, Constructor) { 
    if (!(instance instanceof Constructor)) { 
        throw new TypeError("Cannot call a class as a function"); 
    } 
}
function testable(target) {
  target.isTestable = true;
}
var MyTestableClass = testable(_class = function MyTestableClass() {
  _classCallCheck(this, MyTestableClass);
}) || _class;
console.log(MyTestableClass.isTestable); // true

修饰器函数的第一个参数,就是所要修饰的目标类。
如果觉得一个参数不够用,可以在修饰器外面再封装一层函数。

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

我们来看一个例子:

//多参数修饰器例子
function mixins(...list) {
  return function (target) {
    Object.assign(target.prototype, ...list)
  }
}
const Foo = {
  foo() { console.log('foo') }
};
@mixins(Foo)
class MyClass {}
let obj = new MyClass();
obj.foo() // 'foo'

方法的修饰

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

class Person {
  @readonly
  name() { return `${this.first} ${this.last}` }
}

此时,修饰器函数一共可以接受三个参数,第一个参数是所要修饰的目标对象,第二个参数是所要修饰的属性名,第三个参数是该属性的描述对象。

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),然后被修改的描述对象再用来定义属性。
看一个可以输出方法调用日志的例子:

class Math {
  @log
  add(a, b) {
    return a + b;
  }
}

function log(target, name, descriptor) {
  //获取到原来的方法
  var oldValue = descriptor.value;
  //把新定义的方法给描述符的value
  descriptor.value = function() {
    //输出调用日志
    console.log(`Calling "${name}" with`, arguments);
    //返回原调用结果
    return oldValue.apply(null, arguments);
  };
  return descriptor;
}
const math = new Math();
math.add(2, 4);//Calling "add" with Arguments [2,4]

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

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() {
}

这段代码看起来可以达到效果,但是实际执行时这段代码是这样的:

var counter;
var add;
@add
function foo() {
}
counter = 0;
add = function () {
  counter++;
};

类是不会提升的,所以就没有这方面的问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值