上回书说到我们用了装饰器对我家猫进行了一系列观察,最后我义正言辞的找店家问退货结果被打回来。既然就这样了,那我们就继续观察猫好了。
蕾蒂斯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 的,所以在任何函数的调用后再调用 before , before 的 this 都会指向调用的函数,我们利用闭包先缓存起来这个指向真实方法 eat 这个函数,然后执行 before() 的过程中,将我们的监听合成进去。上述过程,我们利用了两个技术点:
ec 中 this 指向调用者 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 技术黑洞,掌握第一手 撸猫新闻!