The Currization function is a special application of higher order functions. Right, in my opinion: to understand the function coriolization, the pre-knowledge point is only “higher-order function”. Advanced functions for each of us front-end programmers, often used, not difficult. It’s just that we (inexperienced programmers) don’t have a very clear definition of high-level functions. Therefore, this article is divided into two parts: 1. Advanced functions. 2, “special application” advanced functions.)

What are higher-order functions?

  1. If the argument to a function is a function (a callback is a higher-order function)

  2. If a function returns a function, the current function is also a higher-order function

    Example :(both callback functions and return functions as arguments

    // Write a business code that extends the current business codefunctionperson(sex){ console.log(sex); } / / give a method to add a method and before his execution call the Function. The prototype. Before =function (callback) {
       return(... Args)=>{// The rest of the operator, arrow functions do not have this (look up) or arguments (returnA function) callback(); // Execute the passed anonymous function this(... args); // Execute this. Person. before say so say to say-}}let personBornRace = person.before(function(){// Know skin color before birth console.log()'yellow'})// Assign the returned function to beforeSay (parameter function) personBornRace('male'); // the male and female personBornRace('woman');
    Copy the code

    Running results:

    Yellow yellow male femaleCopy the code

2. “Special Application” Advanced Functions (Corrification)

For a hypothetical scenario, do a variable type function (how do we know the type of a variable?). There are four commonly used methods (knowledge supplement) :

  1. Typeof cannot determine object type typeof [] typeof {

  2. Constructor can find out by whom the variable is constructed

  3. Instanceof determines who is whose instance __proto__

  4. Object. The prototype. ToString. Call instance defect is not inferior segment is ()

    We now choose the fourth method to determine the data type function, at this time we can think of:

    /*ps: The following hypothetical scenario and subsequent code is borrowed from someone else. But comments and ideas are the language of their own organization. I originally thought of a lawyer's daily work (take over various types of cases) example, write out after the comparison of others found that it is really not as good as others. So shameless continue to use, as for the original source is already can not give out */function isType(type,value) {
        return Object.prototype.toString.call(value) === `[object ${type}] `; } console.log(isType('Array'[])),Copy the code

    Running results:

    true
    Copy the code

    It’s perfect, isn’t it? It can be done in one sentence. And indeed, in this case, this is really the optimal solution. However, in real development, it is very likely that we need to deal with a large number of different types of variables, and each call requires us to write two parameters, especially the string variable Array. One of them may be written wrong, but the compiler will not report an error, and it is difficult to find the error. As follows:

    console.log(isType([],'Arary'); / / Arary write wrongCopy the code

    Running results:

    false/ /? ? How could it be wrong?Copy the code

    So at this point we wondered if there was one thing we could do, which was to subdivide the method. It’s subdivided into isArray, isString. In English: write one of the variables in advance using a high-level function. You only need to fill in a variable when you call it.

    function isType(type) {
       return function(value) {
           return Object.prototype.toString.call(value) === `[object ${type}]`;
       }
    }
    let isArray = isType('Array'); // We can pass only the variables we want to check. Array has already been written down. console.log(isArray('hello'));
    console.log(isArray([]));
    Copy the code

    Execution Result:

    false
    true
    Copy the code

    The above is the most basic function Coriolization, but if really only so simple, how can deserve such a lofty name Coriolization? How can it be applied to a variety of complex requirements scenarios? Therefore, the above functions can be upgraded and formulated, and a general function can be used in different scenarios.

    General function Cremation (encapsulation) : compare the above code to make sense.

    function isType(type,value) {
        return Object.prototype.toString.call(value) === `[object ${type}] `; } // The general formula can be applied // There is one point here that I do not understand:"type= [] ", declared in parentheses. const currying = (fn,type= = > []) {letlen = fn.length; // This is the length of the function parameter (not called, not yet passed)return function(... args) {let concatValue = [...type,...args];
            if(concatValue.length < len) {
                return currying(fn,concatValue);
            } else {
                returnfn(... concatValue); }}}let isArray = currying(isType)('Array'); // Carry the argument isType, carry the argument "currying"returnThe returned function also passes the argument 'Array' and assigns the last returned fn (which is the isType just passed in) to isArray. The processing looks at the codelet isString = currying(isType)('String');
    console.log(isArray([]))
    console.log(isArray('123'))
    console.log(isString([]));
    console.log(isString('123'));
    Copy the code

    The output

    true
    false
    false
    true
    Copy the code

Ps: I was wondering how to turn the whole above text into a story. Ha ha title overstated, but I should be able to stick to the story: JS magic kingdom, the academy of function engineering magician is doing a day’s work. Graduated from a magic institute of the first order magician Ah Guan today also undertook the same boring work as usual: preparing a series of JS magic kingdom infrastructure project of the basic magic. The magic of adding a and B to get C; Var name=’a’; var name=’a’; Var age = ‘b’) ‘Declarative’ magic ah; Slightly more interesting is the perceptual magic of perceiving the nearest space around you document.getelementById (“box”).offsetwidth.

Today is no exception, he need to put the string ‘https://’, ‘suppliertest.xiaonianyu.com/’, ‘login’ in ‘or’ magic together. In fact, the magician Guan thinks he is quite a genius, because he knows that the magic he prepared today can play the role of teleport after casting (call). ‘Transmission magic ah, even the function engineering academy of the fourth order magician will also be a transmission magic bar! Function research institute of magicians can also make more powerful magic than the magic of transmission to it? ! Big sorcerers sense magic, their own will, and the power is not bad ‘, Ah Guan secretly proud.

It took a while, but Ah Guan finally got the basics right. Now he needs to send this basic magic to his mentor in the engineering academy to go there, on the way ah Guan has been thinking about what he thought just now, the fourth order great magician can do things themselves can do, what is the actual difference between himself and the great magician? Maybe I’ll see my tutor later and if he’s in a good mood, I can ask him for advice.

“Master, I have sent you the basic magic of the union.” “” Yes,” the master quietly added the basic magic to his list. At this time, Ah Guan was observing the teacher’s face and found that he looked kind and in a good mood. So she took the opportunity to ask her question: “Teacher, I found that I can make and fourth-order great wizard magic, and power is the same, I didn’t find where is the difference between I and merlin, take me to you just now for the magic, he can be released after a spell, merlin with me finally make these basic magic magic is a magic.” After listening to my question, the tutor said to me slowly while thinking: “There is nothing wrong with what you said, in so far as the power of two magic is played, but have you ever thought of this spell is js key magic, magic kingdom traffic big infrastructure construction magic, has proved the magic for kingdom all, most of the user is not a spell specialization, Or he didn’t know the exact coordinates of where he was going, just a vague location. Does your magic work when you have these problems?” Here, the tutor stopped, (early morning, don’t write first. I have to work tomorrow. My life matters. To be continued…)