ES6里的修饰器Decorator
修饰器(Decorator)是一个函数,用来修改类的行为。
一、概述
ES6 引入了这项功能,目前 Babel 转码器已经支持Decorator
首先,安装babel-core
和babel-plugin-transform-decorators
。由于后者包括在babel-preset-stage-0
之中,所以改为安装babel-preset-stage-0
亦可
$ npm install babel-core babel-plugin-transform-decorators
然后,设置配置文件.babelrc
{
"plugins": ["transform-decorators"]
}
这时,Babel就可以对Decorator转码了
脚本中打开的命令如下
babel.transform("code", {plugins: ["transform-decorators"]})
二、类修饰
下面代码中,@testable
就是一个修饰器。它修改了MyTestableClass
这个类的行为,为它加上了静态属性isTestable
@testable
class MyTestableClass {
// ...
} function testable(target) {
target.isTestable = true;
} MyTestableClass.isTestable // true
基本上,修饰器的行为就是下面这样
@decorator
class A {} // 等同于 class A {}
A = decorator(A) || A;
修饰器对类的行为的改变,是代码编译时发生的,而不是在运行时。这意味着,修饰器能在编译阶段运行代码,也就是说,修饰器本质就是编译时执行的函数
1、参数
修饰器函数的第一个参数,是所要修饰的目标类
function 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
上面代码中,修饰器testable
可以接受参数,这就等于可以修改修饰器的行为。
前面的例子是为类添加一个静态属性,如果想添加实例属性,可以通过目标类的prototype
对象操作
function testable(target) {
target.prototype.isTestable = true;
} @testable
class MyTestableClass {} let obj = new MyTestableClass();
obj.isTestable // true
三、方法修饰
修饰器不仅可以修饰类,还可以修饰类的属性
class Person {
@readonly
name() { return `${this.first} ${this.last}` }
}
上面代码中,修饰器readonly
用来修饰“类”的name
方法
1、参数
此时,修饰器函数一共可以接受三个参数,第一个参数是所要修饰的目标对象,第二个参数是所要修饰的属性名,第三个参数是该属性的描述对象
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),然后被修改的描述对象再用来定义属性。
下面是另一个例子,修改属性描述对象的enumerable
属性,使得该属性不可遍历
class Person {
@nonenumerable
get kidCount() { return this.children.length; }
} function nonenumerable(target, name, descriptor) {
descriptor.enumerable = false;
return descriptor;
}
2、日志应用
下面的@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(null, arguments);
}; return descriptor;
} const math = new Math(); // passed parameters should get logged now
math.add(, );
上面代码中,@log
修饰器的作用就是在执行原始的操作之前,执行一次console.log
,从而达到输出日志的目的。
修饰器有注释的作用
@testable
class Person {
@readonly
@nonenumerable
name() { return `${this.first} ${this.last}` }
}
从上面代码中,我们一眼就能看出,Person
类是可测试的,而name
方法是只读和不可枚举的
3、执行顺序
如果同一个方法有多个修饰器,会像剥洋葱一样,先从外到内进入,然后由内向外执行
function dec(id){
console.log('evaluated', id);
return (target, property, descriptor) => console.log('executed', id);
} class Example {
@dec()
@dec()
method(){}
}
// evaluated 1
// evaluated 2
// executed 2
// executed 1
上面代码中,外层修饰器@dec(1)
先进入,但是内层修饰器@dec(2)
先执行
除了注释,修饰器还能用来类型检查。所以,对于类来说,这项功能相当有用。从长期来看,它将是JS代码静态分析的重要工具
四、注意事项
修饰器只能用于类和类的方法,不能用于函数,因为存在函数提升
var counter = ; var add = function () {
counter++;
}; @add
function foo() {
}
上面的代码,意图是执行后counter
等于1,但是实际上结果是counter
等于0。因为函数提升,使得实际执行的代码是下面这样
@add
function foo() {
} var counter;
var add; counter = ; 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);
ES6里的修饰器Decorator的更多相关文章
- ES2017中的修饰器Decorator
前面的话 修饰器(Decorator)是一个函数,用来修改类的行为.本文将详细介绍ES2017中的修饰器Decorator 概述 ES2017 引入了这项功能,目前 Babel 转码器已经支持Deco ...
- 修饰器Decorator
类的修饰 许多面向对象的语言都有修饰器(Decorator)函数,用来修改类的行为.目前,有一个提案将这项功能,引入了 ECMAScript. @testable class MyTestableCl ...
- python函数修饰器(decorator)
python语言本身具有丰富的功能和表达语法,其中修饰器是一个非常有用的功能.在设计模式中,decorator能够在无需直接使用子类的方式来动态地修正一个函数,类或者类的方法的功能.当你希望在不修改函 ...
- es6 Decorator修饰器
1.类的修饰: 修饰器(Decorator)函数,用来修改类的行为.修饰器是一个对类进行处理的函数.修饰器函数的第一个参数,就是所要修饰的目标类. @testable class MyTestable ...
- ES6(Decorator(修饰器))
Decorator(修饰器) 1.基本概念 函数用来修改 类 的行为 1.Decorator 是一个函数 2.通过Decorator(修饰器)能修改 类 的行为(扩展 类 的功能)3.Decorato ...
- ES6 Decorator 修饰器
目的: 修改类的一种方法,修饰器是一个函数 编译: 安装 babel-plugin-transform-decortators-legacy .babelrd plugins: [&quo ...
- decorator(修饰器)的业务应用
decrator(修饰器)的业务应用 ES6问世的时间也不短了,而且很多时候对ES6所谓的"熟练应用"基本还停留在下面的几种api应用: const/let 箭头函数 Promis ...
- 19.Decorator修饰器
Decorator 修饰器 类的修饰 许多面向对象的语言都有修饰器(Decorator)函数,用来修改类的行为.目前,有一个提案将这项功能,引入了 ECMAScript. @testable clas ...
- es6 装饰器decorator的使用 +webpack4.0配置
decorator 装饰器 许多面向对象都有decorator(装饰器)函数,比如python中也可以用decorator函数来强化代码,decorator相当于一个高阶函数,接收一个函数,返回一个被 ...
随机推荐
- [poj] 3041 Asteroids || 最小点覆盖=最大二分图匹配
原题 本题为最小点覆盖,而最小点覆盖=最大二分图匹配 //最小点覆盖:用最少的点(左右两边集合的点)让每条边都至少和其中一个点关联. #include<cstdio> #include&l ...
- UltraEdit 删除空行
UltraEdit 删除空行 数据里有大量的空行,想在UltraEdit里删除,在网上搜了很多方法都不管用,功夫不负有心人,最后终于找到了可用的方法: 搜索—>替换,在“查找什么”里输入:\n( ...
- Codeforces Round #328 (Div. 2) B
B. The Monster and the Squirrel time limit per test 1 second memory limit per test 256 megabytes inp ...
- Linux临时增加swap空间
linux临时增加swap空间:step 1: #dd if=/dev/zero of=/home/swap bs=1024 count=500000 注释:of=/home/swap,放置swap的 ...
- 如何在Windows2008中禁用IPv6
我自己修复此问题 更改 DisabledComponents 注册表值 您可以通过将DisabledComponents注册表值的主机上禁用 IPv6.DisabledComponents注册表值会影 ...
- (转)MSI - Enable MSI Logging
转自: http://www.cnblogs.com/atempcode/archive/2007/04/10/707917.html 安装MSI安装包的时候, 有时会遇到错误, 这时LOG文件就非常 ...
- 《Linux命令行与shell脚本编程大全 第3版》创建实用的脚本---11
以下为阅读<Linux命令行与shell脚本编程大全 第3版>的读书笔记,为了方便记录,特地与书的内容保持同步,特意做成一节一次随笔,特记录如下:
- SQLite 字段数据类型
一般数据采用的固定的静态数据类型,而SQLite采用的是动态数据类型,会根据存入值自动判断. SQLite具有以下五种数据类型: 1.NULL:空值. 2.INTEGER:带符号的整型,具体取决有存入 ...
- VS2013 MFC C++ CString ,const char , char, string 类型转换
VS2013 测试 以下测试加入头文件: # include <string>#include <cstdlib>using namespace std; //-------- ...
- windows下利用线程池完成多任务的分配和运行
在做项目的过程中有时候为了提升效率,用了多线程的方法来对任务进行分割和应用,后来发现,采用线程池的方法能更好的利用线程资源来计算任务,网上有很多关于如何运行线程池的例子,msdn上也给出了对应的例子: ...