preface

Presumably you are not unfamiliar with OOP (Object Oriented Programming), it is a Programming idea. AOP(Aspect Oriented Programming) can be said to be a milestone in the history of Programming. Obviously, it is not a substitute for OOP, but a very useful supplement to OOP.

So what exactly is AOP?

We all know that OOP is characterized by inheritance, polymorphism, and encapsulation. Encapsulation is to encapsulate the code of a function into a function (or a class), and then want to implement this function, only need to execute the function method, do not need to repeat the code. There is a problem with this, however, if I encapsulate the functionality of a single TAB that is used in many places in the project. Wouldn’t it be a bad idea to get a request one day that asks for an interface when tabs switch, so that every TAB in the project has to deal with this thing once and write a bunch of code? If I just want to request a certain interface when certain pages switch tabs, then your business code is a lot. This is where aspect processing, or AOP, is needed.

In other words, you’re cutting a watermelon at home, you just cut it, and suddenly you have a visitor… You just want to put a flower on the watermelon, so you make a decorating function, but the rest of the area underneath the watermelon, it’s just one thing or another. By moving to the code level, you do something else with the original business logic without affecting it.

The sample

Function.prototype.before = function(callback) {
  let self = this
  return function() { 
    callback()
    self.apply(self, arguments)}}function fn(. val) {
  console.log('Original function,' + val)
}

let newFn = fn.before(function() { // Execute before the original function
  console.log('Execute before the original function') 
})

newFn('准备'.'execution')  // Pass parameters for the original function
Copy the code

April 28, 2019 (Supplementary)

We can use the after function when dealing with asynchronous concurrency

The sample

let fs = require('fs');
let path = require('path');

// Read the file path
let namePath = path.resolve(__dirname, 'name.txt');
let eagPath = path.resolve(__dirname, 'age.txt')

// Use the after function to simplify asynchronous operations
function after(items, ck) {
  let arr = [];
  return function(err, data) {
    if(err) {
      throw new Error(err);
    }
    arr.push(data); // Pass the result to the corresponding callback
    if(--items === 0) { ck(arr); }}}let newFn = after(2.function(arr) {
  console.log(arr); // Triggers when asynchrony is complete
})

/** * Note: * Asynchrony cannot use try catch */
fs.readFile(namePath, 'utf8'.function(err, data) {
  newFn(err, data)
})

fs.readFile(eagPath, 'utf8'.function(err, data) {
  newFn(err, data)
})
Copy the code