1. Introduction

AOP (Aspect Oriented Programming), meaning: section-oriented Programming, through pre-compilation and runtime dynamic proxy to achieve unified maintenance of program functions of a technology. AOP is a continuation of OOP and a derivative of functional programming. AOP can be used to isolate each part of business logic, thus reducing the degree of coupling between each part of business logic, improving the reusability of programs, and improving the efficiency of development.

2. Basic implementation

For those of you who have used Java Spring, there are three types of notifications: before, after, and around.

We implement these three types of notification when a method is called by JS:

Before (Pre-notification)

As the name implies, it is executed before a function call

Function.prototype.before = function (beforefun) {
  var _orgin = this;    // Save the original function reference
  return function () { // Return the "proxy function" containing the original function and the new function
    beforefun.apply(this.arguments); // Execute a new function to fix this
    return _orgin.apply(this.arguments); // Execute the original function}};var originFun = function(val){
  console.log('Prototype function:'+val);
}

var newFun = originFun.before(function(){
  // Pass in the pre-call method
  console.log('before: ' + new Date().getTime())
})

newFun("Pre-test Notification");

// Call the result
// before: 1557047939699
// Prototype function: pre-test notification
Copy the code

After (post notification)

As opposed to before, it is executed after the function call

Function.prototype.after = function (afterfun) {
  var _orgin = this;    // Save the original function reference
  return function () { // Return the "proxy function" containing the original function and the new function
    var ret = _orgin.apply(this.arguments); // Execute the original function
    afterfun.apply(this.arguments); // Execute a new function to fix this
    returnret; }};var originFun = function(val){
  console.log('Prototype function:'+val);
}

var newFun = originFun.after(function(){
  // Pass in the pre-call method
  console.log('after: ' + new Date().getTime())
})

newFun("Post test notification");

// Call the result
// Prototype function: pre-test notification
// after: 1557047997647
Copy the code

Around (Circular notification)

Execute before and after the method

// Use the previous before, after methods
Function.prototype.around = function(beforeFun, afterFun) {
	var _orgin = this;
	return function() {
		return _orgin.before(beforeFun).after(afterFun).apply(this.arguments); }}Copy the code

3. AOP encounters modifiers

JS has finally added a Decorator function in the ES7 proposal, which is used to modify the behavior of a class, but is now not supported by browsers and needs to be converted using Babel. What happens when AOP is combined with decorators?

logging

AOP in combination with modifiers can be handy for logging or logging function execution times

class Person {
  @log
  say(nick) {
    return `hi ${nick}`; }}function log(target, name, decriptor){
  var _origin = descriptor.value;
  descriptor.value = function(){
    console.log(`Calling ${name} with `, argumants);
    return _origin.apply(null.arguments);
  };

  return descriptor;
}

var person = new Person();
person.say('Ming');
Copy the code

Determine the user login status

class User {
  @checkLogin
  getUserInfo() {
    console.log('Get user information')}}// Check whether the user is logged in
function checkLogin(target, name, descriptor) {
  let method = descriptor.value
  descriptor.value = function (. args) {
    // Verify method, assuming the user name/password can be obtained
    if (validate(args)) {
      method.apply(this, args)
    } else {
      console.log('No login, about to jump to login page... ')}}}let user = new User()
user.getUserInfo()
Copy the code

AOP in React

A good example of using AOP ideas in React is HOC, as shown in the following example

function HOCComp(WrappedComponent){
  return class HOC extends Component {
    render(){
      const newProps = {param: 'HOC'};
      return <div>
        <WrappedComponent {. this.props} {. newProps} / >
      </div>
    }
  }
}

@HOCComp
class OriginComponent extends Component {
  render(){
    return <div>This is the original component {this.props. Param}</div>}}Copy the code

In the example above, we define the new props in HOCComp and pass it in to the child component. We can also process some props in the OriginComponent or rewrap the OriginComponent outer layer. This eliminates the need to modify internal components and preserves functional decoupling.

5. To summarize

AOP ideas are used in many frameworks and projects, including React high-level components, logging, login authentication, Redux middleware, and more. OOP should complement each other in development to improve the robustness and maintainability of software.

The resources

Segmentfault.com/a/119000001…

Blog.csdn.net/qq_21460229…