Home  >  Article  >  Web Front-end  >  Detailed explanation of function Decorator examples in JavaScript

Detailed explanation of function Decorator examples in JavaScript

零下一度
零下一度Original
2017-04-18 11:03:021678browse

This article mainly introduces the JavaScript decorator function (Decorator), and analyzes the function, implementation and usage of the JavaScript decorator function (Decorator) in the form of examples. Friends in need can refer to this article

The example describes the Javascript decorator function (Decorator). Share it with everyone for your reference, the details are as follows:

The decorator function (Decorator) is used to dynamically add a certain function, responsibility, etc. to the object during runtime. Compared with extending the functions of objects through inheritance, decorators are more flexible. First, we can dynamically select a decorator for the object instead of hardcore inheriting the object to implement a certain function point. Secondly: The inheritance method may lead to a large number of subclasses, which is a bit redundant just to add a single function point.

The following are several commonly used decorator function examples. Please check github for related codes.

1 Dynamically add onload listening function


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 Pre-execution function and post-execution function


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');

The execution result is printed on the console as follows:


I am 12 years old
I am Andy
I am Andy
I am a boy

3 Function execution time calculation


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);

Note: I used ES2015 (ES6) syntax here. If you are interested, you can check the previous related content about ES6.

Of course, decorator functions are not limited to these uses. The Nodejs framework Koa used by Tmall is based on decorator functions and ES2015 Generator. I hope this article can serve as a starting point for you to write more elegant JS code.

The above is the detailed content of Detailed explanation of function Decorator examples in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn