本文實例講述了JavaScript裝飾器函數(Decorator)。分享給大家供大家參考,具體如下:
裝飾器函數(Decorator)用于給對象在運行期間動態的增加某個功能,職責等。相較通過繼承的方式來擴充對象的功能,裝飾器顯得更加靈活,首先,我們可以動態給對象選定某個裝飾器,而不用hardcore繼承對象來實現某個功能點。其次:繼承的方式可能會導致子類繁多,僅僅為了增加某一個單一的功能點,顯得有些多余了。
下面給出幾個常用的裝飾器函數示例,相關代碼請查看github。
1 動態添加onload監聽函數
function addLoadEvent(fn) { var oldEvent = window.onload; if(typeof window.onload != 'function') { window.onload = fn; }else { window.onload = function() { oldEvent(); fn(); }; }}function fn1() { console.log('onloadFunc 1');}function fn2() { console.log('onloadFunc 2');}function fn3() { console.log('onloadFunc 3');}addLoadEvent(fn1);addLoadEvent(fn2);addLoadEvent(fn3);
2 前置執行函數和后置執行函數
Function.prototype.before = function(beforfunc) { var self = this; var outerArgs = Array.prototype.slice.call(arguments, 1); return function() { var innerArgs = Array.prototype.slice.call(arguments); beforfunc.apply(this, innerArgs); self.apply(this, outerArgs); };};Function.prototype.after = function(afterfunc) { var self = this; var outerArgs = Array.prototype.slice.call(arguments, 1); return function() { var innerArgs = Array.prototype.slice.call(arguments); self.apply(this, outerArgs); afterfunc.apply(this, innerArgs); };};var func = function(name){ console.log('I am ' + name);};var beforefunc = function(age){ console.log('I am ' + age + ' years old');};var afterfunc = function(gender){ console.log('I am a ' + gender);};var beforeFunc = func.before(beforefunc, 'Andy');var afterFunc = func.after(afterfunc, 'Andy');beforeFunc('12');afterFunc('boy');
執行結果,控制臺打印如下:
I am 12 years oldI am AndyI am AndyI am a boy
3 函數執行時間計算
function log(func){ return function(...args){ const start = Date.now(); let result = func(...args); const used = Date.now() - start; console.log(`call ${func.name} (${args}) used ${used} ms.`); return result; };}function calculate(times){ let sum = 0; let i = 1; while(i < times){ sum += i; i++; } return sum;}runCalculate = log(calculate);let result = runCalculate(100000);console.log(result);
注:這里我使用了ES2015(ES6)語法,如果你感興趣可以查看前面關于ES6的相關內容。
當然,裝飾器函數不僅僅這些用法。天貓使用的Nodejs框架Koa就基于裝飾器函數及ES2015的Generator。希望這篇文章能起到拋磚引玉的作用,使你編寫更優雅的JS代碼。
更多關于JavaScript相關內容可查看本站專題:《javascript面向對象入門教程》、《JavaScript中json操作技巧總結》、《JavaScript切換特效與技巧總結》、《JavaScript查找算法技巧總結》、《JavaScript動畫特效與技巧匯總》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答