项目场景:
最近做了一个功能,需要在执行完的函数后面添加事件处理其他东西,但是这个函数不是自己系统,苦恼怎么加类似监听完成呀,后面返现个有趣的东西。
问题描述
譬如,引用了外部系统js链接<script href="外部js链接"></script>,该js中包含handle()方法
,需要在handle()执行完自己的方法mySelfHandle()。
//外部js function handle(){ console.log('handle'); } //自己的js function mySelfHandle(){ console.log('mySelfHandle'); } handle(); mySelfHandle(); //貌似这样也可以,但是发现很多地方调用了handle();
//这就需要下面的全局给handle扩展功能了
处理方式
先定义前后置方法,再给handle添加前后置方法
//定义执行前方法
var functionBefore = function(targetFn, beforeFn){
return function(){
beforeFn.apply(this, arguments);
return targetFn.apply(this, arguments);
}
}
//定义执行后方法
var functionAtfer = function(targetFn, afterFn){
return function(){
var rs = targetFn.apply(this, arguments);
afterFn.apply(this, arguments);
return rs;
}
}
//添加执行前方法
handle = functionBefore(handle, function(){
console.log('哈哈');
});
//添加执行后方法
handle = functionAtfer(handle, mySelfHandle);
//执行外部方法
handle();
结果:
这样,只要全局给handle添加前后置方法,就不需要改动其它地方了