JS

Decorator(装饰器)

By John Han
Picture of the author
Published on
async 异步

Decorator(装饰器)

装饰器(Decorator)是一种与类(class)相关的语法,用来注释或修改类和类方法。

装饰器(Decorator)的主要作用是:在多个类之间共享或者扩展类的方法,是一种非侵入式的行为修改

可以让我们的代码更加简洁、易懂。

1. Decorator 的用法

@tag
class A {
@method
hi() {}
}

function tag(constructor) {
console.log(constructor === A); // true
}

function method(target) {
console.log(target.constructor === A, target === A.prototype); // true, true
}

上面这段代码是无法在浏览器中直接执行的,我们需要用 Babel 把它编译成 ES5 的语法。

上面@tag是一个装饰器,它用来修饰class A;

上面@method也是一个装饰器,它用来修饰类的方法hi;

2. Decorator 的本质

Decorator是Object.defineProperty()的语法糖。

3. Decorator 的妙用

试一试

用 Babel 看看把装饰器编译成什么了

参考

Javascript 装饰器的妙用

Stay Tuned

Want to become a Next.js pro?
The best articles, links and news related to web development delivered once a week to your inbox.