1. CoreFn core module implemented the previous method

(1) Demand, inThe core logicExecute before you implementBefore methodTo isolate generic code from core logic

For example, the logic to determine whether a user is logged in or not, and the ability to create before interceptors

(2) Implementation code

function coreFn(params) {
  console.log('coreFn: Core Logic ', params);
}
function beforeFn() {
  console.log('beforeFn: Core logic executes before execution ');
}
coreFn.before = function (beforeFn) {
  return (. args) = > {
    // beforeFn
    console.log('Say beforeFn');
    beforeFn();
    // Core logic
    this(... args); }; };let newFn = coreFn.before(beforeFn);
newFn();
Copy the code

2. Optimize your code: Make before onePublic module

(1) Existing problems:

Now, the before method is attached to coreFn, so if this is a new coreFn2 and you want to implement the before method, then the code can only be copied and cannot be reused.

The solution is to put the before method on the Function prototype chain

(2) Implementation code

function coreFn(params) {
  console.log('coreFn: Core Logic ', params);
}
function beforeFn() {
  console.log('beforeFn: Core logic executes before execution ');
}
Function.prototype.before = function (beforeFn) {
  return (. args) = > {
    // beforeFn
    console.log('Say beforeFn');
    beforeFn();
    // Core logic
    this(... args); }; };let newFn = coreFn.before(beforeFn);
newFn('Here are the request parameters');

Copy the code

3. About this pointing problem in code:

The before method’s this point intercepts the preceding code

Function.prototype.before = function (beforeFn) {
  return (. args) = > {
    // beforeFn ...
    // Core logic
    this(... args); }; };let newFn = coreFn.before(beforeFn);
Copy the code

– In general, the delta functionThis points to theThe object that executes this method,

For arrow functions, no prototype chain, no arguments, no this, then the arrow function’s this depends on the context of this

– Arrow function this example:

For example, this(… This in args), which is performing the normal function function(beforeFn){}, is coreFn

Because coreFn. Before (beforeFn)

4. Concept extension of higher-order functions

A higher-order function satisfies one of the following conditions

(1) The arguments to a function are functions

Function fn(()=>{})

(2) The return value of a function is a function, such as a closure

The before method above is also a higher-order function