欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

ES7装饰器语法

发布时间:2024/1/8 编程问答 38 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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(){} 是 会报错的

class Person{constructor(){this.firstName = 'A'this.lastName = 'b'}@readonlyname(){return `${this.firstName} ${this,this.lastName}`} }function readonly(target,name,descriptor){descriptor.writable = falsereturn descriptor; }const p = new Person() console.log(p.name());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)

总结

以上是生活随笔为你收集整理的ES7装饰器语法的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。