ES7装饰器语法
文章目录
- 装饰类
- 初识
- 简单用lol皮肤概念于装饰器模式
- 装饰方法
- 案例1:修改方法的特性
- 案例二:为添加日志
装饰类
ES7的装饰器完全是在装饰器模式的基础上产生的,关于装饰器模式,可以点击这里先理解一波。
初识
下面直接看Demo
装饰Demo @testDec // testDec是一个函数 class Demo{}function testDec(target){ //这里的target就是Demotarget.isDec = true //添加一个装饰的属性 }alert(Demo.isDec)上面的代码一般可以改成这样传参的形式:
function tesDec(arg){return function(target){target.isDec = arg} }@tesDec(false) class Demo {}alert(Demo.isDec)简单用lol皮肤概念于装饰器模式
function BuySkin(...skin){return function(target){Object.assign(target.prototype,...skin) //对象的合并} }// 皮肤对象 const LeeSkin = {LongXia(){console.log('使用龙瞎');},ZGZQ(){console.log('使用至高之拳');},ShenLong(){console.log('使用神龙尊者');} }// 将皮肤对象装饰到LeeQin对象 @BuySkin(LeeSkin) class LeeQin{constructor(){this.originalSkin = '盲仔'} }const leeQin = new LeeQin() leeQin.LongXia() leeQin.ZGZQ() leeQin.ShenLong()装饰方法
其实下面的所有需求,应该也是可以用ES6proxy实现的
案例1:修改方法的特性
实现被装饰后的方法是不能改写的,只能够读,用装饰模式
所以p.name = function(){} 是 会报错的
但是需要注意的是被装饰后的方法是不能改写的,只能够读 所以const p.name = function(){} 是 会报错的
案例二:为添加日志
function log(target,name,descriptor){let oldValue = descriptor.valuedescriptor.value = function(){console.log(`calling ${name} with `,arguments);return oldValue.apply(this,arguments)}return descriptor }class Math{@logadd(a,b){return a+b} }let math = new Math()const res = math.add(1,2)总结
- 上一篇: matlab-simulink-sims
- 下一篇: systemd 介绍