Understanding JavaScript inline naming functions - -- var fun = function f() {}

Keywords: Javascript

When using JavaScript recursive calls, we often call the function itself (through the function name) within the function, but when we change the direction of the function name used when defining, the recursive function associated with the recursive function pointer will also fail.
    var factorial = function (num) {
        if (num <= 1) {
            return 1;
        } else {
            return num * factorial(num - 1);
        }
    };
    console.log(factorial(5)); // 120;
    var anothorFactorial = factorial;
    factorial = null;
    console.log(anothorFactorial(5)); // Uncaught TypeError: factorial is not a function

In the non-strict mode, we can use num * arguments. callee (num-1) instead of the function name.
In strict mode, inline naming functions are usually used to solve this problem.

    var factorial = (function f(num) {
        if (num <= 1) {
            return 1;
        } else {
            return num*f(num - 1);
        }
    });
    console.log(factorial(5)); // 120
    var anothorFactorial = factorial;
    factorial = null;
    console.log(anothorFactorial(5)); // 120

Function calls in this way are different from those in the following ways:

     function f(num) {
        if (num <= 1) {
            return 1;
        } else {
            return num*f(num - 1);
        }
    };
    var factorial = f;
    var anothorFactorial = factorial;
    factorial = null;
    console.log(anothorFactorial(5)); // 120
    f = null;
    console.log(anothorFactorial(5)); // Uncaught TypeError: f is not a function

Naming an anonymous function of a function expression does not change the nature of the expression, that is, it does not make it a function declaration.

    var factorial = function f() {
        console.log(factorial == f); // true
    }

    factorial(); //true
    console.log(typeof f); // undefined
    f(); // Uncaught ReferenceError: f is not defined

The above code proves that although we can name inline functions, these names can only be visible inside our own functions. Using inline method to call, its essence and function expression are not very different. The only difference is that inline named function provides a function pointer within the function that can only be called by itself, which points to the function itself.

Posted by purefusion on Thu, 14 Feb 2019 14:30:18 -0800