Home  >  Article  >  Web Front-end  >  Characteristics of JavaScript function expressions and understanding of recursion (with examples)

Characteristics of JavaScript function expressions and understanding of recursion (with examples)

不言
不言forward
2018-10-25 15:40:361847browse

What this article brings to you is about the characteristics of JavaScript function expressions and the understanding of recursion (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Function expressions are a powerful yet confusing feature of JavaScript.

There are two ways to define functions: one is function declaration, and the other is function expression.

The syntax of function declaration is like this.

function functionName(arg0, arg1, arg2) {
    //函数体
}

Syntax: First the function keyword, then the name of the function. This is how the function name is specified.

Firefox, Safari, Chrome and Opera all define a non-standard name attribute for functions, through which the name specified for the function can be accessed.
The value of this attribute is always equal to the identifier following the function keyword.

//只在Firefox、Safari、Chrome和Opera有效
function functionName(arg0, arg1, arg2) {
}
console.log(functionName.name); // "functionName"

Regarding function declaration, one of its important features is function declaration hoisting, which means that the function declaration is read before executing the code. This means that the function declaration can be placed after the statement that calls it.

sayName(); // "Shaw"
function sayName(){
    console.log("Shaw");
}

This example will not throw an error because the function declaration will be read before the code is executed

The second way to create a function is to use function expression.

Function expressions have several different syntax forms.
The following is the most common form.

var functionName =  function(arg0, arg1, arg2) {
    //functionBody
};

This form looks like a regular variable assignment statement, that is, creating a function and assigning it to the variable functionName.

The function created in this case is called anonymous function (anonymous function), because there is no identifier after the function keyword.
Anonymous functions are also called lambda functions. The name attribute of the anonymous function is a null character.

Function expressions, like other expressions, must be assigned a value before use.

sayHi(); // error : sayHi is not a function
var sayHi = function(){
    console.log("Hi");
}
// var sayHi //此时sayHi是undefined
// sayHi() // error : sayHi is not a function
// sayHi = function() { console.log("Hi");}

The key to understanding function promotion is to understand the difference between function declarations and function expressions.

You can create a function and assign it to a variable, and you can also return the function as the value of other functions.

function createComparisonFunction(propertyName) {
    return function(object1, object2) {
        var value1 = object1[propertyName];
        var value2 = object2[propertyName];
        if(value1 < value2) {
            return -1
        }else if(value1 > value2) {
            return 1;
        } else {
            return 0;
        }
    }
}

createComparisonFunction() returns an anonymous function.
The returned function may be assigned to a variable or called in other ways.
However, inside the createComparisonFunction() function, it is anonymous.
Anonymous functions can be used when functions are used as values.
However, this is not the only use of anonymous functions.

Recursion

A recursive function is formed when a function calls itself through the function name.

function factorial(num) {
    if(num <= 1) {
        return 1;
    } else {
        return num * factorial(num-1);
    }
}
factorial(4); // 4*3*2*1 = 24

//4* factorial(3) => 4*3*factorial(2) => 4*3*2*factorial(1) => 4*3*2*1 => 24

This is a classic recursive factorial function. Although this function looks fine on the surface, the following code may cause it to error.

function factorial(num) {
    if(num <= 1) {
        return 1;
    } else {
        return num * factorial(num-1);
    }
}
var anotherFactorial = factorial;
factorial = null;
//注意这里,其实函数factorial指向一个空对象。
console.log(anotherFactorial(4));  //Error: anotherFactorial is not a function

The above code first saves the factorial() function in the variable anotherFactorial, and then sets the factorial variable to null. As a result, there is only one reference to the original function.
But when anotherFactory() is called next, factorial() must be executed, and factorial is no longer a function, so an error will occur.

Google Chrome tested the above code and it didn’t work. It is recommended not to understand this part in depth.
In this case, using arguments.callee can solve the problem.

arguments.callee is a pointer to the executing function, so it can be used to implement recursive calls to the function.

function factorial(num) {
    if(num <= 1) {
        return 1;
    } else {
        return num * arguments.callee(num-1);
    }
}

"return num * arguments.callee(num-1);" By using arguments.callee instead of the function name, you can ensure that there will be no problem no matter how you call the function.
Therefore, when writing recursive functions, it is always safer to use arguments.callee than using function names.

But in strict mode, arguments.callee cannot be accessed through scripts, and accessing this property will cause an error.

But we can use named function expressions to achieve the same result.

var factorial = function f(num){
    if(num <= 1) {
        return 1;
    } else {
        return num * f(num-1);
    }
}

//factorial 指向了函数f

var anotherFactorial = factorial;
//anotherFactorial 指向了函数f

factorial = null;
//factorial 指向了一个空对象。

anotherFactorial(4); //24
////anotherFactorial 指向了函数f, 所以还可以正常调用。

The above code creates a named function expression named f(), and then assigns it to the variable factorial.
Even if the function is assigned to another variable, the function name f is still valid, so the recursive call can still be completed correctly.
This method works in both strict mode and non-strict mode.

The above is the detailed content of Characteristics of JavaScript function expressions and understanding of recursion (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete