首頁  >  文章  >  web前端  >  JavaScript中函數Decorator實例詳解

JavaScript中函數Decorator實例詳解

零下一度
零下一度原創
2017-04-18 11:03:021634瀏覽

這篇文章主要介紹了JavaScript裝飾器函數(Decorator),結合實例形式分析了JavaScript裝飾器函數(Decorator)的功能、實作與使用方法,需要的朋友可以參考下

本文實例講述了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 old
I am Andy
I am Andy
I 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中函數Decorator實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn