本教程操作环境:windows10系统、ecmascript 6.0版、dell g3电脑。
es6装饰器有几种es6装饰器有两种。
装饰器(decorator)是一种与类(class)相关的语法,用来注释或修改类相关的方法和属性。许多面向对象的语言都有这个功能。一般和类class相关,普通的方法不要去使用。
装饰器是一种函数,写成@ + 函数名。它可以放在类和类方法的定义前面。装饰器就是执行函数,给类或者类下面的属性方法加一些控制条件。
装饰器只能用于类和类的方法,不能用于函数,因为存在函数提升。
1、类装饰器
类装饰器用来装饰整个类
示例如下:
@decorateclassclass example { //...} function decorateclass(target) { target.istestclass = true}
如上面代码中,装饰器 @decorateclass 修改了 example 整个类的行为,为 example 类添加了静态属性 istestclass。装饰器就是一个函数,decorateclass 函数中的参数 target 就是 example 类本身,也相当于是类的构造函数 example.prototype.constructor.
2、类方法装饰器
类方法装饰器用来装饰类的方法
示例如下:
class example { @log instancemethod() { } @log static staticmethod() { }} function log(target, methodname, descriptor) { const oldvalue = descriptor.value; descriptor.value = function() { console.log(`calling ${name} with`, arguments); return oldvalue.apply(this, arguments); }; return descriptor;}
如上面代码中,装饰器 @log 分别装饰了实例方法 instancemethod 和 静态方法 staticmethod。@log 装饰器的作用是在执行原始的操作之前,执行 console.log 来输出日志。
【相关推荐:javascript视频教程、web前端】
以上就是es6装饰器有几种的详细内容。
