从撸猫到AOP的思考,程序员的大脑究竟在想什么Part. 2

767 阅读2分钟

连载-02、黑魔法带你魔改

上回书说到我们用了装饰器对我家猫进行了一系列观察,最后我义正言辞的找店家问退货结果被打回来。既然就这样了,那我们就继续观察猫好了。

蕾蒂斯and箭头们,肥少又回来了,本期我们将继续思考AOP,啊不是,撸猫。没事看着这个小动物也挺无聊的,除了吃就是睡,我观察了8个小时,这货真的是除了吃就是睡!(催稿人:你tm闲8个小时不写稿)

上一季中,我们写了个装饰器,这样WatchCat这个类的所有方法我们都可以监听了。换句话说,就是我们可以在React的体系中进行监控,很多写vue的小伙伴们跑过来问我,那么在vue中,我也想监听要怎么办咧?

环境: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()的过程中,将我们的监听合成进去。上述过程,我们利用了两个技术点:

  • 函数的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!

好了,简单的讲完了这些,看一眼我们的小芝麻还在睡得很香呢。

本期就讲这些了,撸猫去咯~

记得关注 ihap 技术黑洞,掌握第一手 撸猫新闻!