decorator 装饰器
许多面向对象都有decorator(装饰器)函数,比如python中也可以用decorator函数来强化代码,decorator相当于一个高阶函数,接收一个函数,返回一个被装饰后的函数。
注: javascript中也有
decorator相关的提案,只是目前node以及各浏览器中均不支持。只能通过安装babel插件来转换代码,插件名叫这个:
transform-decorators-legacy。也有在线试用](https://babeljs.io/repl/),安装好
transform-decorators-legacy之后,就能看到转义后的代码了:
[code]npm i -D @babel/plugin-proposal--decorators
可以再下载一个plugin配置类里面属性的写法
[code]npm i -D @babel/plugin-proposal-class-properties
在babelrc中配置插件:
[code]options: { plugins: ['@babel/plugin-proposal-class-properties'] }
2.1 使用decorator的前期配置
1.vscode里面去除装饰器报错的方法
在vscode里打开设置=>用户设置里面加入(tips:打开设置后也可以直接点击右上角的'{}'进行用户设置)
[code]"javascript.implicitProjectConfig.experimentalDecorators": true
就可以了。
2.搭建一个简单的webpack 来使用装饰器
由于目前浏览器和node暂时不支持装饰器,所以我们可以配置一个webpack来使用装饰器
全局安装:
[code] cnpm install webpack webpack-cli webpack-dev-server -g
启动配置 创建一个webpack.dev.js
[code]var path = require('path') module.exports = { mode: "development", entry: { main: "./test.js" }, output: { path: path.resolve(__dirname, "./dist"), filename: "test.js" }, module: { rules: [ //webpack 4.X写法 { test: /.js$/, use: ['babel-loader'] } ] } }
下载依赖(webpack4.x 方法 )
[code]npm install -D babel-loader @babel/core @babel/preset-env
配置.babelrc
[code]{ "presets": [ "@babel/preset-env" ], "plugins": [ [ "@babel/plugin-proposal-decorators", { "legacy": true } ], ] }
创建好webpack的目录结构是这样的
package.json的配置
[code]{ "name": "decorator", "version": "1.0.0", "description": "", "main": "test.js", "scripts": { "build": "webpack --config=webpack.dev.js", "start": "node ./dist/bound.js" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "@babel/core": "^7.4.4", "@babel/plugin-proposal-class-properties": "^7.4.4", "@babel/plugin-proposal-decorators": "^7.4.4", "@babel/preset-env": "^7.4.4", "babel-loader": "^8.0.5", "babel-plugin-transform-decorators-legacy": "^1.3.5", "babel-preset-env": "^1.7.0", "core-decorators": "^0.20.0" } }
2.2 开始使用decorator
1.类的修饰
许多面向对象的语言都有修饰器(Decorator)函数,用来修改类的行为。目前,有一个提案将这项功能,引入了 ECMAScript。 下面我们采用一个钢铁侠的例子来展开
[code]@transform class IronMan { // ... } function transform(target) { target.weapon = 'laser' } console.log(IronMan.weapon) // laser
上面代码中,@transform就是一个修饰器。它修改了
IronMan这个类的行为,为它加上了武器属性
weapon。
transform函数的参数
target是
IronMan类本身。
2.方法的修饰
修饰器不仅可以修饰类,还可以修饰类的属性。
[code]class Person { @readonly name() { return `${this.first} ${this.last}` } }
上面代码中,修饰器
readonly用来修饰“类”的
name方法。
修饰器函数
readonly一共可以接受三个参数。
[code]function readonly(target, name, descriptor){ // descriptor对象原来的值如下 // { // value: specifiedFunction, // enumerable: false, // configurable: true, // writable: true // }; descriptor.writable = false; return descriptor; } Person.prototype.name="韩梅梅" console.log(Person.prototype.name)//fn 修饰的是类的原型 readonly(Person.prototype, 'name', descriptor); // 类似于 Object.defineProperty(Person.prototype, 'name', descriptor);
修饰器第一个参数是类的原型对象,上例是
Person.prototype,修饰器的本意是要“修饰”类的实例,但是这个时候实例还没生成,所以只能去修饰原型(这不同于类的修饰,那种情况时
target参数指的是类本身);第二个参数是所要修饰的属性名,第三个参数是该属性的描述对象。
4.装饰器不能用于修饰函数
原本作者设计的时候 是可以使用这种方式的 比如修饰一个函数这么写
[code]@RunOnce function expensiveOperation() { return 1 + 1; } //语法糖之后的效果是这样的 var expensiveOperation = RunOnce(function expensiveOperation() { return 1 + 1; });
这意味着装饰器可以用于任何任务,但是作者认为这样可能有点复杂 并且还有一个潜在的问题 装饰器和跟随变量一块提升 使得装饰器语法函数过早执行而导致因为位置的原因产生的一些错误 比如:
[code]var readOnly = require("some-decorator"); // 是否提升求值? // 如果是这样的话 `readOnly` 那么就是未定义 @readOnly function foo() { }
总而言之,作者不希望产生这样的复杂性,所以去除了修饰函数,详情可以参考这篇作者参与讨论的帖子
5.应用
至于decorator的应用场景在哪里?应该大部分AOP的场景都可以用,例如日志系统。 这里就手动来实现一个简单的日志系统。
[code]const log = (type) => { return (target, name, descriptor) => { let method = descriptor.value; // 具体三个方法 let result = method() console.log(`${type}${result}成功`) } } class Man { @log('正在洗漱') wash() { return "洗漱"; } @log('正在吃饭') eat() { return "吃饭"; } @log('正在跑步') run() { return "跑步"; } } let m = new Man(); m.wash() m.eat(); m.run();
6.core-decorators.js
core-decorators.js是一个第三方模块,提供了几个常见的修饰器,通过它可以更好地理解修饰器。
(1)@readonly
readonly修饰器使得属性或方法不可写。
[code]import { readonly } from 'core-decorators'; class Meal { @readonly entree (){ console.log(111) }; } var dinner = new Meal(); dinner.entree = 'salmon'; // Cannot assign to read only property 'entree' of [object Object]
(2)@override
override修饰器检查子类的方法,是否正确覆盖了父类的同名方法,如果不正确会报错。
[code]import { override } from 'core-decorators'; class Parent { speak(first, second) {} } class Child extends Parent { @override speak() {} // SyntaxError: Child#speak() does not properly override Parent#speak(first, second) } // or class Child extends Parent { @override speaks() {} // SyntaxError: No descriptor matching Child#speaks() was found on the prototype chain. // // Did you mean "speak"? }
(3)@deprecate (别名@deprecated)
deprecate或
deprecated修饰器在控制台显示一条警告,表示该方法将废除。
[code]import { deprecate } from 'core-decorators'; class Person { @deprecate facepalm() {} @deprecate('We stopped facepalming') facepalmHard() {} @deprecate('We stopped facepalming', { url: 'http://knowyourmeme.com/memes/facepalm' }) facepalmHarder() {} } let person = new Person(); person.facepalm(); // DEPRECATION Person#facepalm: This function will be removed in future versions. person.facepalmHard(); // DEPRECATION Person#facepalmHard: We stopped facepalming person.facepalmHarder(); // DEPRECATION Person#facepalmHarder: We stopped facepalming // // See http://knowyourmeme.com/memes/facepalm for more details. //
- Decorator(装饰)模式
- 装饰模式(Decorator Pattern)
- (C++设计模式) ------Decorator装饰模式-- 结构型模式
- Java开发中的23种设计模式之七:装饰模式(Decorator)
- Java私塾:研磨设计模式 之 装饰模式(Decorator)3
- 设计模式之美:Decorator(装饰)
- Decorator(装饰)模式
- Python之装饰器(Decorator)
- 设计模式之装饰器模式(decorator pattern)
- 函数式编程--装饰器(Decorator)
- 设计模式-装饰模式(Decorator Pattern)
- 设计模式09: Decorator 装饰模式(结构型模式)
- c++设计模式----Decorator(装饰)
- 我的java设计模式 总结【5】装饰器 Decorator
- 第六章 装饰器模式 (Decorator)
- 深入浅出设计模式(九):12.装饰模式(Decorator) 13.桥模式(Bridge)14.策略模式(Strategy)
- 7、装饰模式(Decorator)
- 设计模式(八)装饰器模式Decorator(结构型)
- 设计模式总结之装饰模式 (Decorator)
- 结构型模式:DECORATOR——装饰模式