当前位置: 首页 > Web前端 > JavaScript

函数式编程之AOP面向切面编程

时间:2023-03-27 16:00:36 JavaScript

鍋囪鎴戜滑鐩墠鏈変竴涓皬闇€姹傦細瀹炵幇鐩爣鍑芥暟璋冪敤鍓嶅悗鐨勪笟鍔¢€昏緫鏂规硶銆?/intro瀹炵幇璋冪敤娴嬭瘯鍑芥暟鍓嶅悗鐨勪笟鍔¢€昏緫鏂规硶锛沠unctiontest(){console.log(2);};//璋冪敤鍑芥暟test();//expect鏈熸湜杈撳嚭濡備笅//console.log(1);//console.log(2);//console.log(3);鎯虫兂鎴戜滑灏嗗浣曞疄鐜拌繖涓€鐩爣锛燄煠旔煠旈毦鐐癸細1.缁戝畾鐨勬柟娉曞湪鍝噷锛?.鍑芥暟鐨勬墽琛岄『搴忋€?.濡備綍淇濊瘉杩欎竴鐐癸紵4.鍙傛暟濡備綍淇濊瘉锛熸€濊矾锛氬叾瀹炴垜浠煡閬搄s浠g爜涓殑浠讳綍涓€涓嚱鏁伴兘鏄疐unction鏋勯€犲嚱鏁扮殑涓€涓疄渚嬪璞°€傜敱浜庤瀹炵幇棰濆鐨勫姛鑳斤紝鎵€浠ュ繀椤婚噸鍐欏嚱鏁版湰韬紝涔熷氨鏄竴涓叏鏂扮殑鍑芥暟锛屾墍浠ユ柟娉曞彲浠ョ粦瀹氬埌鍘熷瀷涓婄殑鎵€鏈夊嚱鏁帮紱瀹炵幇濡備笅锛?/intro瀹炵幇娴嬭瘯鍑芥暟璋冪敤鍓嶅悗鐨勪笟鍔¢€昏緫鏂规硶锛沠unctiontest(){console.log(2);};//缁戝畾鏂规硶Function.prototype.before=function(beforeFn){const_this=this;//娴嬭瘯璋冪敤鎸囧悜鍘熷鍑芥暟returnfunction(){//杩斿洖涓棿鍑芥暟beforeFn();//鍓嶇疆鍑芥暟_this();//鍘熷嚱鏁版祴璇晑;};Function.prototype.after=function(afterFn){const_this=this;//涓棿鍑芥暟returnfunction(){//鏈€缁堥噸鍐欑殑娴嬭瘯鍑芥暟_this();//涓棿鍑芥暟afterFn();//鍚庣疆鍑芥暟};};//閲嶅啓test=test.before(function(){console.log(1);}).after(function(){console.log(3);})//璋冪敤鍑芥暟test();//杈撳嚭濡備笅//console.log(1);//console.log(2);//console.log(3);杩欐牱灏卞彲浠ュ疄鐜板嚱鏁拌皟鐢ㄥ墠鍚庣殑涓氬姟閫昏緫鏂规硶銆侷mperfect锛氫篃鏄繖涓寚鍚戠殑缁忓吀闂銆傚嚱鏁扮殑鑷皟鐢ㄦ槸鍦ㄩ缂栬瘧杩涚▼涓墽琛岀殑锛宼his浼氭寚鍚戠獥鍙c€傜湅鐪嬩笅闈㈢殑浠g爜functiontest(){console.log(this);//绐楀彛};Function.prototype.before=function(beforeFn){const_this=this;杩斿洖鍑芥暟锛堬級{beforeFn锛堬級;_杩欙紙锛?};};Function.prototype.after=function(afterFn){const_this=this;杩斿洖鍑芥暟锛堬級{_this锛堬級锛涘悗Fn();};};test=test.before(function(){console.log(this);//绐楀彛}).after(function(){console.log(this);//绐楀彛})//璋冪敤鍑芥暟test();缂哄皯闂锛熻繖涓偣鎬庝箞淇濊瘉锛熷嚱鏁版祴璇曪紙锛墈console.log锛堣繖涓級锛?/obj};Function.prototype.before=function(beforeFn){const_this=this;returnfunction(){console.log(this)//this=>Tagthis=>objbeforeFn.call(this);_this.call(this);};};Function.prototype.after=function(afterFn){const_this=this;returnfunction(){//鏍囩console.log(this);//閭i噷浠?>test.call(obj)=>obj_this.call(this);//鍐嶆璋冪敤call鏂规硶鑾峰彇_this鍑芥暟鐨則his=>objafterFn.call(this);};};-----------------//浣跨敤瀵硅薄constobj={test:test;}-----------------//娉ㄦ剰宸﹁竟test鐨勫疄闄呭嚱鏁版槸Tag澶勬爣璁扮殑鍑芥暟test=obj.test.before(function(){console.log(this);//obj}).after(function(){console.log(this);//obj})//铏界劧浣跨敤浜嗗璞★紝浣唗his浠嶇劧娌℃湁鏀瑰彉銆傛垜浠娇鐢╟all鏂规硶灏嗗叾鏇存敼涓烘寚鍚憈est.call(obj);杩樹笉澶熷畬鍠勶細濡備綍淇濊瘉鍙傛暟鐨勪紶閫掞紵鍔熻兘娴嬭瘯锛坅锛宐锛宑锛墈鎺у埗鍙般€傛棩蹇楋紙[a锛宐锛宑]锛夛紱//['涓€浜屼笁']};鍔熻兘銆傚師鍨嬨€俠efore=function(beforeFn){const_this=this;returnfunction(){beforeFn.apply(this,arguments);_this.apply锛堣繖涓紝鍙傛暟锛夛紱};};Function.prototype.after=function(afterFn){const_this=this;returnfunction(){//鏍囩console.log(arguments);//arguments瀹炲弬鍒楄〃銆佺被鏁扮粍鍜屽舰鍙傛槧灏刜this.apply(this,arguments);afterFn.apply(this,arguments);};};constobj={test:test;}test=obj.test.before(function(a,b,c){console.log([a,b,c]);//['涓€','浜?,'涓?]}).after(function(a,b,c){console.log([a,b,c]);//['涓€','浜?,'涓?]})test.call(obj,'涓€浜屼笁'锛?//杈撳嚭//['one','two','three']//['one','two','three']//['one','two','three']鏈€鍚庢垜浠畬鍏ㄥ疄鐜颁簡杩欎釜灏忚姹倊~