從擼貓到AOP的思考,程序員的大腦究竟在想什麼Part. 2

連載-0二、黑魔法帶你魔改

上回書說到咱們用了裝飾器對我家貓進行了一系列觀察,最後我義正言辭的找店家問退貨結果被打回來。既然就這樣了,那咱們就繼續觀察貓好了。javascript

蕾蒂斯and箭頭們,肥少又回來了,本期咱們將繼續思考AOP,啊不是,擼貓。沒事看着這個小動物也挺無聊的,除了吃就是睡,我觀察了8個小時,這貨真的是除了吃就是睡!(催稿人:你tm閒8個小時不寫稿)vue

上一季中,咱們寫了個裝飾器,這樣WatchCat這個類的全部方法咱們均可以監聽了。換句話說,就是咱們能夠在React的體系中進行監控,不少寫vue的小夥伴們跑過來問我,那麼在vue中,我也想監聽要怎麼辦咧?java

環境:vue2+緩存

本次採起的方式是魔改的方式拓展Function.prototype,看了這麼久的 ihap 技術黑洞,此次終於能夠學到真正的黑魔法了。閉包

Function.prototype.before = function() {
    const __self = this;
    return function(...args) {
        console.log('hi, ihap is watching before you!');
        return __self.apply(this, args);
    }
}

const cat = {
    eat: function() {
        console.log('my cat is eatting!');
    }.before(),
};

cat.eat();
// hi, ihap is watching before you!
// my cat is eatting!
複製代碼

哦?這麼神奇,爲何呢?哎,在咱們公衆號的前幾篇關於ec的文章中,咱們着重的講了this的指向問題。從上面的代碼中,咱們能夠看到this是綁定到Function.prototype的,因此在任何函數的調用後再調用beforebeforethis都會指向調用的函數,咱們利用閉包先緩存起來這個指向真實方法eat這個函數,而後執行before()的過程當中,將咱們的監聽合成進去。上述過程,咱們利用了兩個技術點:app

  • 函數的ecthis指向調用者
  • 閉包殘留住this

瞭解了上述魔法以後,咱們要開始準備大張旗鼓了!函數

// hijack.js
Function.prototype.start = function() {
    const __self = this;
    return function(...args) {
        console.log('ohhhhhh, monitor start');
        return __self.apply(this, args);
    }
}

Function.prototype.photo = function() {
    const __self = this;
    return function(...args) {
        const result = __self.apply(this, args);
        console.log('ohhhhhh, look! my cat is eatting!');
        return result;
    }
}

複製代碼
<template>
	<div>123</div>
</template>
<script>
export default {
    data() {
        return {};
    },
    mounted() {
        this.catMove();
        this.catEat();
    },
    method: {
        catMove: function() {
            console.log('cat start to move!');
        }.start(),
        catEat: function() {
            console.log('cat is eatting!');
        }.photo(),
    }
}
</script>
複製代碼

當咱們調用catMove的時候,咱們的監控就開啓了,ohhhhhh, monitor start就被打印出來了,而後纔會打印cat start to move!。當咱們調用catEat方法的時候,會先執行cat is eatting!而後再執行ohhhhhh, look! my cat is eatting!ui

好了,簡單的講完了這些,看一眼咱們的小芝麻還在睡得很香呢。this

本期就講這些了,擼貓去咯~spa

記得關注 ihap 技術黑洞,掌握第一手 擼貓新聞!

相關文章
相關標籤/搜索