您的位置:首页 > Web前端 > JavaScript

分析一段JS 动态织入代码

2015-07-27 23:13 836 查看
Function.prototype.before=function(beforefn){ var_self=this; returnfunction(){ beforefn.apply(this,arguments); return_self.apply(this,arguments); } } Function.prototype.after=function(afterfn){ var_self=this; returnfunction(){ varret=_self.apply(this,arguments); afterfn.apply(this,arguments); returnret; } } varfunc=function(){ console.log(2); } func=func.before(function(){ console.log(1); }).after(function(){ console.log(3); }) func();

  这里所谓的JS动态织入算是一种模式。

  代码最终执行的返回结果是打印出

  1

  2

  3

  

之前自己一直理解不了打印出123的原因,总以为应该是1223,23便是after()中打印出来的值。

但其实当连续调用func.before().after()的时候,其次after中的var_self=this;其实表示的是before()的返回值,根据代码,返回值是

returnfunction(){
beforefn.apply(this,arguments);
return_self.apply(this,arguments);
}


带入到整理当中最终执行的便是

func=func.before(function(){ console.log(1); }).after(function(){ console.log(3); })
(function(){
beforefn.apply(this,arguments);  //打印出1
return_self.apply(this,arguments);//打印出2
})();

(function(){ console.log(3);  //打印出3 });


  所以最终的结果也就是123,并且之所以能够链式调用是因为before()返回值也是一个函数,所以也存在after()方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: