javascript AOP

What is AOP

Aspect Oriented Programming An abbreviation for aspect, it is a method that allows you to describe various inseparable parts of a program as an aspect by extracting common processing across the board. Java--768x508.jpg Image source: Spring AOP Tutorial – AOP for Beginners with Examples

javascript AOP

There are various methods, but this time I will introduce Function.prototype as an example.

//Define before function
Function.prototype.before = function( functionBefore ) {
  var _this = this;
  //Return the original function and functionBefore respectively
  return function() {
    functionBefore.apply(this, arguments);
    return _this.apply(this, arguments);
  }
};
//Define after function
Function.prototype.after = function( functionAfter ) {
  var _this = this;
  return function() {
    var result = _this.apply(this, arguments);
    functionAfter.apply(this, arguments);
    return result;
  }
};
//Prepare a test function
var fn = function() {
  console.log('fn is running');
};
// before()And after()To "add" to the test function
fn = fn.before(function(){
  console.log('start!');
}).after(function(){
  console.log('end!');
});

fn();

The result is: console.png

It turns out that'start!',' Fn is running', and'end!' Are displayed in sequence.

Uses of AOP

--Logging process as described above --Transaction processing --Error handling

Common mechanism such as.

Recommended Posts

javascript AOP
JavaScript basics
JavaScript function
JavaScript array manipulation
About Spring AOP
About spring AOP
Java and JavaScript