ES6装饰器

1.类的装饰

@testable
class MyTestableClass {
  // ...
}

function testable(target) {
  target.isTestable = true;
}

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

基本上,装饰器的行为就是如下,也就是说,装饰器是一个对类处理的函数,装饰器的第一个参数,就是要处理的目标类

@decorator
class A {}

// 等同于

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

如果一个参数不够用,还可以在外面封装一层函数

function testsAble(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

装饰器对类方法的复制

// 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的实例上面。
可以用Object.assign()模拟这个功能。

2.类方法的装饰器

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

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

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

装饰器第一个参数是类的原型对象,上例是Person.prototype,装饰器的本意是要“装饰”类的实例,但是这个时候实例还没生成,所以只能去装饰原型(这不同于类的装饰,那种情况时target参数指的是类本身);第二个参数是所要装饰的属性名,第三个参数是该属性的描述对象。


下面是另一个例子,修改属性描述对象的enumerable属性,使得该属性不可遍历。

class Person {
  @nonenumerable
  get kidCount() { return this.children.length; }
}

function nonenumerable(target, name, descriptor) {
  descriptor.enumerable = false;
  return descriptor;
}

使用装饰器语法的vue类组件

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

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

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)先执行。


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

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

var counter = 0;

var add = function () {
  counter++;
};

@add
function foo() {
}

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

var counter;
var add;

@add
function foo() {
}

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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值