最近從朋友那邊白嫖了一隻貓,提及這個擼貓,真是不得了,太有癮了,擼起來就停不下來,這可愛的小傢伙喵喵喵的,真是萌翻了。早上餵了早飯,鏟了屎就去上班了。javascript
中午 12:00,我開始躁動不安了,我家貓咋樣了,是否是餓着了,是否是渴了。有沒有拆我家電視,有沒有撓個人沙發,不行了,awsl,我要知道我家貓在幹啥。java
這不就是 AOP 嘛,恰好最近正好工做有用到了 AOP,那咱們不得不說一下什麼是 AOP?編程
面向切面編程,旨在經過容許跨領域關注點的分離來提升模塊化。一般呢是經過不修改代碼自己的狀況下向現有代碼添加其餘行爲,目標是一個切入點,切面,因此也就有了面向切面編程這個說法。值得一提的是,AOP 是一種編程規範,並非一種純粹的技術,他只提供了定義,具體實現仍是有不少種的,比較常見的就是裝飾器的形式。app
function business() {
console.log('I will do some business!');
}
async function asyncBusiness() {
await new Promise(resolve => setTimeout(() => resolve('ohhhhhhhhhh'), 3000));
console.log('I will do some async business!');
}
function monitor(callback) {
return async function() {
console.log('monitor start');
const result = await callback.apply(this, arguments);
console.log('monitor end');
return result;
};
}
const monitorBusiness = monitor(business);
const monitorAsyncBusiness = monitor(asyncBusiness);
business();
monitorBusiness();
await asyncBusiness();
await monitorAsyncBusiness();
複製代碼
其實一個裝飾器就是這麼簡單,那麼咱們常見的@的形式來實現的裝飾器是什麼樣的呢?@形式的裝飾器實際上是利用了 Object.defineProperty。async
Object.defineProperty(obj, prop, descriptor)
obj
The object on which to define the property.prop
The name or Symbol of the property to be defined or modified.descriptor
The descriptor for the property being defined or modified.模塊化
詳細的內容不在本期講解,若是有興趣,請關注咱們的公衆號 ihap 技術黑洞 ,以後我纔會告訴你在 MDN 的連接是ui
不關注的大家就不知道了!spa
回到咱們的裝飾器上,那麼怎麼寫一個在類裏可使用的裝飾器呢?3d
ok, 逼格 than 逼格,讓咱們優雅的在代碼裏逼格一下!
class WatchCat {
@log
eat() {
console.log('cat is eatting');
}
@log
drink() {
console.log('cat is drink');
}
}
function log(target) {
if (target.kind === 'method') {
const original = target.descriptor.value;
target.descriptor = {
...target.descriptor,
async value(...args) {
try {
console.log('I am watching my cat!');
const result = await original.apply(this, args);
console.log('I am finished watch my cat!');
return result;
} catch (err) {
console.error('sorry, my cat broken my monitor');
throw err;
}
},
};
}
return target;
}
const watchCat = new WatchCat();
watchCat.eat();
複製代碼
這樣,在咱們對貓進行觀察的時候,貓並無產生什麼反應,仍是在吃飯。
好了,我決定買個攝像頭來監視個人貓天天究竟在幹嗎
實際上它天天我不在的時候就在吃睡,怪不得天天晚上都是這麼精神。
好了,本次的肥少帶你擼貓之旅就到此結束了。不說了,問問客服能不能退貨,攝像頭徹底沒有意義了。
自此感謝咱們 ihap 技術黑洞 的鎮號之寵——芝麻!友情出演。
喜歡的老闆們記得關注點贊喲。
大家是否是覺得沒了?哈哈哈哈哈哈哈,忽然想起來忘記給大家講@log('ihap 技術黑洞')若是有參數的形式,要怎麼寫了。
function log(name) {
return target => {
if (target.kind === 'method') {
const original = target.descriptor.value;
target.descriptor = {
...target.descriptor,
async value(...args) {
try {
console.log(`${name} is watching my cat!`);
const result = await original.apply(this, args);
console.log(`${name} is finished watch my cat!`);
return result;
} catch (err) {
console.error('sorry, my cat broken my monitor');
throw err;
}
},
};
}
return target;
};
}
複製代碼
好了,真的沒有了,你們白白!
參考文獻: stackoverflow.com/questions/8… www.sitepoint.com/javascript-… developer.mozilla.org/en-US/docs/…