Appearance
装饰器
已有功能较为完好的模块,在不改动这部分模块的情况下,扩展功能。
- JS中的Function类
javascript
Function.prototype.before = function(beforeFn){
var _this = this;
return function(){
beforeFn.apply(this.arguments);
return _this.apply(this, arguments);
}
};
Function.prototype.after = function(afterFn){
var _this = this;
return function(){
var ret = _this.apply(this, arguments);
afterFn.apply(this, arguments);
return ret;
}
};
// ============ 上方代码是重点 ============
function test(){
console.log("111")
}
var test1 = test.before(()=>{
console.log("000")
}).after(()=>{
console.log("222")
})
test1()
小例子
javascript
/*
<button id="filmbtn">点击上传电影信息</button>
*/
Function.prototype.before = function(beforeFn){
var _this = this;
return function(){
beforeFn.apply(this.arguments);
return _this.apply(this, arguments);
}
};
Function.prototype.after = function(afterFn){
var _this = this;
return function(){
var ret = _this.apply(this, arguments);
afterFn.apply(this, arguments);
return ret;
}
};
function log(){
console.log("上传pv数据")
}
function render(){
console.log("页面逻辑处理")
}
render = render.before(log)
// 标签id可以直接使用
filmbtn.onclick = function(){
render()
}