Details of the JavaScript function pattern

  • 2020-03-30 04:14:12
  • OfStack

In javascript, a function is a class of object, which means it can be passed as an argument to another function. In addition, functions can provide scope.

Basic part of js function: (link: #)

Create the syntax for the function

Named function expression


//Named function expression
var add = function add(a,b){
    return a+b;
};

Functional expression


//Also known as the anonymous function
var add = function(a,b){
    return a+b;
};

Declaration of functions


function foo(){
    //code here
}  //You don't need a semicolon

In trailing semicolons, function expressions should always use semicolons, and semicolon endings are not required in function declarations.

Function declarations and expressions

The ascension of function (hoisting)

The behavior of the function declaration is not the same as named function expressions, the difference is that ascension (hoisting) behavior, look at the following examples:


<script type="text/javascript">
    //Global function
    function foo(){alert("global foo!");}
    function bar(){alert('global bar');}     function hoist(){
        console.log(typeof foo);//function
        console.log(typeof bar);//undefined         foo();//local foo!
        bar();//TypeError: 'undefined' is not a function          //The variable foo and implementer are promoted
        function foo(){
            alert('local foo!');
        }         //Only the variable bar is promoted, the function implementation part is not promoted
        var bar = function(){
            alert('local bar!');
        };
    }
    hoist();
</script>

For all variables, no matter where they are declared in the body of the function, they are raised internally to the top of the function. This is generally true for functions because functions are simply objects assigned to variables.

Promotion, as the name implies, is to bring the following things up. In JS, you are lifting something (a variable or function) defined in the back to the previous definition. As you can see from the above example, the foo and bar in the function hoist were moved to the top to override the global foo and bar functions. The difference between the local function bar and foo is that foo is promoted to the top and works, whereas the definition of bar() is not promoted, only its declaration is promoted, so that when bar() is executed the result is undefined instead of being used as a function.

Immediate function mode

Functions are also objects, so they can be used as return values. The advantage of using the self-executing function is to directly declare an anonymous function, immediately use, save the definition of a function that is not used once, and avoid the problem of naming conflict, js does not have the concept of namespace, so it is easy to have a name conflict, once the name conflict to the last declaration.

A model:


<script>
    (function () {
        var a = 1;
        return function () {
            alert(2);
        };
    }()());//Pop 2, the first parenthesis executes itself, the second parenthesis executes the inner anonymous function
</script>

Pattern 2: direction of self-executing function variables


<script type="text/javascript">
        var result = (function () {
            return 2;
        })();//The function has been executed here         alert(result);//Result points to the return value 2 from the self-executing function; If result() pops up, an error occurs
</script>

Pattern 3: nested functions


<script type="text/javascript">
        var result = (function () {
            return function () {
                return 2;
            };
        })();  alert(result());//Alert (result) pops up 2; Alert (result()) brings up function(){return 2}
</script>

Pattern 4: a self-executing function assigns its return value to a variable


    var abc = (function () {
            var a = 1;
            return function () {
                return ++a;
            }
        })();//The self-executing function returns the function after return to the variable
   alert(abc());//If alert(ABC) pops up the code after the return statement; If it's ABC (), the return function
is executed

Pattern 5: functions execute themselves internally, recursively


//This is a self-executing function that executes itself internally, recursively
function abc() { abc(); }

The callback mode

Callback function: when you pass a function write() as an argument to another function call(), at some point call() might perform (or call) write(). In this case, write() is called a callback function.

Asynchronous event listener

The callback pattern has many USES, for example, when an event listener is attached to an element on the page, it actually provides a pointer to a callback function that will be called when the event occurs. Such as:


document.addEventListener("click",console.log,false);

The code example above shows what happens when a document clicks on an event and is passed in bubbling mode to the callback function console.log()

timeout

Another example of using the callback pattern is when using the timeout methods provided by the browser's window object: setTimeout() and setInterval(), such as:


<script type="text/javascript">
    var call = function(){
        console.log("100ms will be asked ... ");
    };
    setTimeout(call, 100);
</script>

The callback pattern in the library

Callbacks come in handy when designing a js library, where code should be as reusable as possible, and callbacks can help with this generalization. When we design a large js library, in fact, users won't need most of the functionality, and we can focus on the core functionality and provide callback functions in "hook form," which will make it easier to build, extend, and customize library methods

Curry,

Currying is a technique for transforming a function into a new, simplified (and less parameterized) function by populating the body with multiple arguments. -- [proficient in JavaScript]

Currying is simply a process of transformation, the process by which we perform a function transformation. Here's an example:


<script type="text/javascript">
    //Curried add() function
    function add(x,y){
        var oldx = x, oldy = y;
        if(typeof oldy == "undefined"){
            return function(newy){
                return oldx + newy;
            };
        }
        //Fully apply
        return x+y;
    }
    //The test < br / >     typeof add(5);//Output "function" < br / >     add(3)(4);//7
    //Create and store a new function
    var add2000 = add(2000);
    add2000(10);//The output of 2010 < br / > </script>

When add() is first called, it creates a closure for the returned inner function. This closure stores the original x and y values in private variables oldx and oldy.

Now we can use the generic method of any function curry, such as:


<script type="text/javascript">
    //Normal function
    function add(x,y){
        return x + y;
    }
    //Curried a function to get a new function
    var newadd = test(add,5);
    newadd(4);//9     //Alternatively, call the new function
directly     test(add,6)(7);//The output of 13 < br / > </script>

When to use currying

When you find that the same function is being called and that the arguments passed are overwhelmingly the same, the function can be a good candidate for currying


Related articles: