ES7装饰器语法
文章目錄
- 裝飾類
- 初識(shí)
- 簡單用lol皮膚概念于裝飾器模式
- 裝飾方法
- 案例1:修改方法的特性
- 案例二:為添加日志
裝飾類
ES7的裝飾器完全是在裝飾器模式的基礎(chǔ)上產(chǎn)生的,關(guān)于裝飾器模式,可以點(diǎn)擊這里先理解一波。
初識(shí)
下面直接看Demo
裝飾Demo @testDec // testDec是一個(gè)函數(shù) class Demo{}function testDec(target){ //這里的target就是Demotarget.isDec = true //添加一個(gè)裝飾的屬性 }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) //對(duì)象的合并} }// 皮膚對(duì)象 const LeeSkin = {LongXia(){console.log('使用龍瞎');},ZGZQ(){console.log('使用至高之拳');},ShenLong(){console.log('使用神龍尊者');} }// 將皮膚對(duì)象裝飾到LeeQin對(duì)象 @BuySkin(LeeSkin) class LeeQin{constructor(){this.originalSkin = '盲仔'} }const leeQin = new LeeQin() leeQin.LongXia() leeQin.ZGZQ() leeQin.ShenLong()裝飾方法
其實(shí)下面的所有需求,應(yīng)該也是可以用ES6proxy實(shí)現(xiàn)的
案例1:修改方法的特性
實(shí)現(xiàn)被裝飾后的方法是不能改寫的,只能夠讀,用裝飾模式
所以p.name = function(){} 是 會(huì)報(bào)錯(cuò)的
但是需要注意的是被裝飾后的方法是不能改寫的,只能夠讀 所以const p.name = function(){} 是 會(huì)報(bào)錯(cuò)的
案例二:為添加日志
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)總結(jié)
- 上一篇: matlab-simulink-sims
- 下一篇: systemd 介绍