类的修饰

许多面向对象的语言都有修饰器(Decorator)函数,用来修改类的行为。目前,有一个提案将这项功能,引入了 ECMAScript。

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

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

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

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

也就是说,修饰器是一个对类进行处理的函数。修饰器函数的第一个参数,就是所要修饰的目标类。

function testable(target) {
// ...
}

上面代码中,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

上面代码中,修饰器函数testable是在目标类的prototype对象上添加属性,因此就可以在实例上调用。

下面是另外一个例子。

// 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()模拟这个功能。

const Foo = {
foo() { console.log('foo') }
}; class MyClass {} Object.assign(MyClass.prototype, Foo); let obj = new MyClass();
obj.foo() // 'foo'

实际开发中,React 与 Redux 库结合使用时,常常需要写成下面这样。

class MyReactComponent extends React.Component {}

export default connect(mapStateToProps, mapDispatchToProps)(MyReactComponent);

有了装饰器,就可以改写上面的代码。

@connect(mapStateToProps, mapDispatchToProps)
export default class MyReactComponent extends React.Component {}

相对来说,后一种写法看上去更容易理解。

方法的修饰

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

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参数指的是类本身);第二个参数是所要修饰的属性名,第三个参数是该属性的描述对象。

另外,上面代码说明,修饰器(readonly)会修改属性的描述对象(descriptor),然后被修改的描述对象再用来定义属性。

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

class Person {
@nonenumerable
get kidCount() { return this.children.length; }
} function nonenumerable(target, name, descriptor) {
descriptor.enumerable = false;
return descriptor;
}

下面的@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(this, arguments);
}; return descriptor;
} const math = new Math(); // passed parameters should get logged now
math.add(2, 4);

上面代码中,@log修饰器的作用就是在执行原始的操作之前,执行一次console.log,从而达到输出日志的目的。

修饰器有注释的作用。

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

从上面代码中,我们一眼就能看出,Person类是可测试的,而name方法是只读和不可枚举的。

下面是使用 Decorator 写法的组件,看上去一目了然。

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

除了注释,修饰器还能用来类型检查。所以,对于类来说,这项功能相当有用。从长期来看,它将是 JavaScript 代码静态分析的重要工具。

为什么修饰器不能用于函数?

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

var counter = 0;

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

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

@add
function foo() {
} var counter;
var add; 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);
转自阮一峰http://es6.ruanyifeng.com/#docs/decorator
仅供个人学习和交流

ES6---修饰器的更多相关文章

  1. ES6里的修饰器Decorator

    修饰器(Decorator)是一个函数,用来修改类的行为. 一.概述 ES6 引入了这项功能,目前 Babel 转码器已经支持Decorator 首先,安装babel-core和babel-plugi ...

  2. es6 Decorator修饰器

    1.类的修饰: 修饰器(Decorator)函数,用来修改类的行为.修饰器是一个对类进行处理的函数.修饰器函数的第一个参数,就是所要修饰的目标类. @testable class MyTestable ...

  3. ES6入门六:class的基本语法、继承、私有与静态属性、修饰器

    基本语法 继承 私有属性与方法.静态属性与方法 修饰器(Decorator) 一.基本语法 class Grammar{ constructor(name,age){ //定义对象自身的方法和属性 t ...

  4. ES6(Decorator(修饰器))

    Decorator(修饰器) 1.基本概念 函数用来修改 类 的行为 1.Decorator 是一个函数 2.通过Decorator(修饰器)能修改 类 的行为(扩展 类 的功能)3.Decorato ...

  5. ES6 Decorator 修饰器

    目的:  修改类的一种方法,修饰器是一个函数 编译: 安装 babel-plugin-transform-decortators-legacy .babelrd      plugins: [&quo ...

  6. ES6学习笔记九:修饰器

    一:修饰器(Decorator)是一个函数,用来修改类的行为. 1)定义与使用 function 修饰器名(target) { //target是被修饰对象,可用target.xxx进行调用修改 } ...

  7. decorator(修饰器)的业务应用

    decrator(修饰器)的业务应用 ES6问世的时间也不短了,而且很多时候对ES6所谓的"熟练应用"基本还停留在下面的几种api应用: const/let 箭头函数 Promis ...

  8. 19.Decorator修饰器

    Decorator 修饰器 类的修饰 许多面向对象的语言都有修饰器(Decorator)函数,用来修改类的行为.目前,有一个提案将这项功能,引入了 ECMAScript. @testable clas ...

  9. 修饰器Decorator

    类的修饰 许多面向对象的语言都有修饰器(Decorator)函数,用来修改类的行为.目前,有一个提案将这项功能,引入了 ECMAScript. @testable class MyTestableCl ...

  10. Python 从零学起(纯基础) 笔记 之 迭代器、生成器和修饰器

    Python的迭代器. 生成器和修饰器 1. 迭代器是访问集合元素的一种方式,从第一个到最后,只许前进不许后退. 优点:不要求事先准备好整个迭代过程中的所有元素,仅仅在迭代到某个元素时才计算该元素,而 ...

随机推荐

  1. vue单页面应用加入百度统计

    版权声明:本文为CSDN博主「钟文辉」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明.原文链接:https://blog.csdn.net/qq_39753974/a ...

  2. Ubuntu安装opencv3.4.4教程

    1 去官网下载opencv 在本教程中选用的是opencv3.4.4,下载链接 http://opencv.org/releases.html ,选择sources. 2 解压 unzip openc ...

  3. DBShop前台RCE

    前言 处理重装系统的Controller在判断是否有锁文件后用的是重定向而不是exit,这样后面的逻辑代码还是会执行,导致了数据库重装漏洞和RCE. 正文 InstallController.php中 ...

  4. lumen路由配置nginx

    nginx配置文件中添加: set   $root_path   '/data/www/m.domain.com/public';    root   $root_path; location / { ...

  5. shell 函数的高级用法

    函数介绍 linux shell中的函数和大多数编程语言中的函数一样 将相似的任务或者代码封装到函数中,供其他地方调用 语法格式 如何调用函数 shell终端中定义函数 [root@master da ...

  6. drf-过滤组件|分页组件|过滤器

    目录 drf-过滤组件|分页组件|过滤器 群查接口各种筛选组件数据准备 drf过滤组件 搜索过滤组件 | SearchFilter 案例: 排序过滤组件 | OrderingFilter 案例: dr ...

  7. Excel导入+写入数据库

    1.引用服务 2.前端 <h2>这里是上传Excel功能页面</h2> <div> <form action="/Improve_Excel/get ...

  8. 记一次SQL PLUS 不能登录的异常处理

    记一次SQL PLUS 不能登录的异常处理 现象 通过远程PLSQL Developer 访问数据发现卡死没响应. 通过Sqlplus 访问数据同样hang死在登录界面,且不能通过Ctrl+C取消 [ ...

  9. Java基本知识点o(1), o(n), o(logn), o(nlogn)的了解

    在描述算法复杂度时,经常用到o(1), o(n), o(logn), o(nlogn)来表示对应算法的时间复杂度, 这里进行归纳一下它们代表的含义: 这是算法的时空复杂度的表示.不仅仅用于表示时间复杂 ...

  10. SQL Server 2005的几个新功能

    SQL Server 2005相对于SQL Server 2000改进很大,有些还是非常实用的. 举几个例子来简单说明 这些例子我引用了Northwind库. 1. TOP 表达式  SQL Serv ...