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 介绍