Function and closure summary

One, function

Function: Encapsulation body of n statements

  • create
  1. function Function name (){} Declared function:
    Once declared, it is called globally (don’t care about the writing position).
  2. var Function name = function(){} Function expression:
    If an anonymous function has a name, the name becomes invalid.
  3. **Constructor var function name = new Function(parameter, statement) **Not commonly used
  • Attributes
    -name The name of the function
    -length returns the number of formal parameters of the function

  • Formal parameters, actual parameters
    - the number of shape parameters> excess number of arguments is undefined parameter values
    - the number of shape parameters <real number in the parameter extra arguments in the argument
    -arguments: The collection of all actual parameters is a pseudo-array, which is often used to implement functions with indefinite parameters
    -arguments.callee is a reference to the function in non-strict mode. Strict mode is not available.

  • The difference between a simple type value as an argument and a reference type as an argument:
    1. Simple type value as a parameter, changes inside the function will not affect the passed variable
    2. Reference type value as a parameter, changes inside the function will affect the passed variable
    -default parameter short-circuit statement

  • return value
    -If return is not written, it will return undefined by default

  • Function scope
    -You can use external functions or window variables inside-You can
    not use function internal variables outside of functions
    -Execute functions immediately (create independent space) Immediate execution of function expressions 3

  • Advanced functions: A function that takes a function as a parameter or return value

    • Closure: A function that can access variables in the scope of another function
  • Function declaration promotion> Variable declaration promotion

1. Indefinite function arguments
 function add(){
    
    
            var count = 0;
            for(var i = 0; i < arguments.length; i ++){
    
    
                count += arguments[i];
            }
            return count;
        }

        var returnValue = add(1,2); // 3
2. ES6 indefinite parameters (...args) The set of parameters other than the known parameters
    // 剩余参数必须写在末尾
  function add2(a,b, ...args){
    
    
    console.log(args);
}
add2(1,2,3,4,5); //    [3,4,5]
3. Default parameters
  function mul(a, b){
    
    
            // 如果没有a, a = 2
            // 如果没有b, b = 3
            a = a || 2;
            b = b || 3;
            
            return a * b;
        }
        console.log(mul()); // 6
function mul1(a = 3, b = 2){
    
    
            console.log("默认参", a * b);
        }
        mul1(); // 6
        mul1(4); // 8
        mul1(undefined, 4); // 12
4.obj.assign merged objects
  function sayName(obj){
    
    
            obj = Object.assign({
    
    
                name: "xx"
            }, obj);
            console.log(obj.name);
        }
        sayName(); // "xx"
        sayName({
    
    }); // "xx"
        sayName({
    
     name: "李白"}); // "李白"
5. In the scope of the environment: first the function declaration is promoted, and then it is the turn of the variable declaration to promote.
 var a = 10;
        function fn(){
    
    
            
            console.log(a); // undefined
            return; 
            a += 30;
            var a = 20;
            console.log(a); 
        }

        fn();
        console.log(a); // 10
6. Execute the function immediately
// 1. 函数表达式的立即执行
var fn = function (){
    
    
	console.log("函数表达式的立即执行");
}();
// 2. 声明函数的立即执行
(function fn(){
    
    
	console.log("立即执行");
}())
(function fn(){
    
    
	console.log("立即执行");
})()
// 3. 函数表达式使用两个括号时
var fn = (function(){
    
    
	console.log("函数表达式的立即执行");
}())
var fn = (function(){
    
    
	console.log("函数表达式的立即执行");
})()
7. Closure questions

The essence of a closure is: it refers to a function that has access to a variable in the scope of another function.

 function fun(n, o) {
    
    
            console.log(o);
            return {
    
    
                fun: function (m) {
    
    
                    return fun(m, n);
                }
            };
        }
第一道:
        // var a = fun(0); // undefined
        // a.fun(1); // 0     
        // a.fun(2); // 0
        // a.fun(3); // 0
第二道:链式操作

        // var b = fun(0).fun(1).fun(2).fun(3); // undefined 0 1 2
第三道:
        var c = fun(0).fun(1); // undefined 0
        c.fun(2); // 1
        c.fun(3); // 1
  • effect:

    • Extend the life cycle of local variables
    • Let the function outside the internal local variables can be manipulated
  • The scope chain of a closure contains its own scope, as well as the scope and global scope of the function that contains it

  • Closure application:

    • Callback
    • Modular coding: Encapsulate some data and functions to manipulate data, and expose some behaviors
    • Add event listener for traversal
  • Disadvantages:

    • Variables may take too long to occupy memory

    • May cause memory leaks

    • Solution: Release in time: f = null; // Make the internal function object a garbage object

  • Closure question 2

 // 闭包题1:编写一个像 sum(a)(b) = a+b 这样工作的 sum 函数。
        function sum(a, b) {
    
    
            return function (b) {
    
    
                console.log(a + b);
            }
        }
        sum(3)(-4);
  • Closure Problem 3
    // Closure question 2: Simplify sort to sort by field
        // 有一组需要排序的对象
        let users = [
            {
    
     name: "John", age: 20, surname: "Johnson" },
            {
    
     name: "Pete", age: 18, surname: "Peterson" },
            {
    
     name: "Ann", age: 19, surname: "Hathaway" }
        ];

        // 通常的做法:

        // 通过 name (Ann, John, Pete)
        users.sort(function (a, b) {
    
     return a.name > b.name ? 1 : -1 });
        console.log(users);
        // 通过 age (Pete, Ann, John)
        // users.sort(function (a, b) {
    
     return a.age > b.age ? 1 : -1 });
        // console.log(users.sort());

        // 要求简化为: 根据key升序排列
        function byField(key) {
    
    
            return function (a, b) {
    
    
                return a[key] > b[key] ? 1 : -1;
            }
        }
        users.sort(byField('name'));
        console.log(users);

        users.sort(byField('age'));
        console.log(users);
// 排序后修改对象数组地址,以前打印的同一堆地址的对象数组,所以结果都一致。

Guess you like

Origin blog.csdn.net/weixin_47067248/article/details/107966491