There are two main methods for creating functions in JavaScript: function declarations and function expressions. Both methods have different applicable scenarios. This note mainly focuses on several major characteristics of function expressions and their usage scenarios, which are described below.
Main features
• Optional function name
The function name is a necessary part of the function declaration. This function name is equivalent to a variable. The newly defined function will be copied to this variable. The call to the function needs to be performed through this variable in the future. For function expressions, the name of the function is optional, for example:
var sub = function(a1,a2){ return a1-a2; }In this example, the function expression has no name and belongs to anonymous function expression. Let’s take a look at the following example:
var sub = function f(a1,a2){ return a1-a2; } console.log(f(5,3)); //Incorrect call method console.log(sub(5,3)); //Correct call methodIn this example, the name of the function expression is f. This name f actually becomes a local variable inside the function and refers to the function object itself. It is of great use when function recursive, and will be discussed in detail later.
•Create during the execution phase (different from function declarations)
This feature is that the function expression is obviously different from the function declaration.
The interpreter does not treat both methods equally when parsing JavaScript code. The interpreter will first read the function declaration and make it available before executing any code; while for function expressions, you must wait until the interpreter executes to the line of code where it is located before it will be actually parsed and executed. For example:
console.log(add(1,2)); //"3" console.log(sub(5,3)); //"unexpected identifier", error function add(a1,a2){ return a1+a2; } var sub = function(a1,a2){ return a1-a2; }The first statement can be executed normally. When evaluating the code, the JavaScript engine declares functions on the first pass and places them on the top of the source tree through a process called function declaration promotion. That is to say, during the creation stage of the execution environment (the function is called but has not started execution), the function declaration will be "hosting". So, even if the code that declares a function is behind the code that calls it, the JavaScript engine will lift the function declaration to the top. However, if the function declaration is changed to a function expression, an error will be reported during execution. The reason is that before executing the statement where the function is located, the variable sub does not contain a reference to the function. That is to say, the variable sub will be assigned during the code execution stage. Except for the above differences, in other aspects, the syntax of function declarations and function expressions is equivalent.
•Do not affect variable objects
var sub = function f(a1,a2){ console.log(typeof f); //"function" return a1-a2; } console.log(typeof f); //"Uncaught ReferenceError: f is not defined(…)"From the above example, we can see that the function name f can only be used inside the function object, and the function name of the function expression does not exist in the variable object.
Use scenarios
There are many usage scenarios for function expressions. The following mainly describes the applications of function recursion and code modularity.
• Function recursion
See the following example:
function factorial(num){ if(num <= 1){ return 1; }else{ return num * factorial(num - 1); } }This is a classic factorial function, but one problem with this example is that the function name factorial is closely coupled to the function body. If you execute the following statement, you will get an error:
var anotherFactorial = factorial; factorial = null; console.log(anotherFactorial(5)); //"Uncaught TypeError: factorial is not a function"
The reason for an error is that the factorial function will be called inside the function body, and the reference to the function by the variable factorial has been cancelled, so an error is reported. The solution to this situation can generally be solved using arguments.callee, which always points to the current function, for example:
function factorial(num){ if(num <= 1){ return 1; }else{ return num * arguments.callee(num - 1); } }In this way, you can get the correct result by executing anotherFactorial function here. However, under strict mode "strict", arguments.callee cannot be accessed through scripts. This is how to solve this problem using function expressions, for example:
var factorial = (function f(num){ if(num <= 1){ return 1; }else{ return num * f(num - 1); } }); console.log(factorial(5)); //"120"•Code modularity
There is no block-level scope in JavaScript, but we can use function expressions to modularize JavaScript code. The modular code can encapsulate details that do not need to be known to the user, and only expose them to the relevant interfaces of the user, while avoiding pollution to the global environment, such as:
var person = (function(){ var _name = ""; return{ getName:function(){ return _name; }, setName:function(newname){ _name = newname; } }; }()); person.setName("John"); person.getName(); //"John"In this example, an anonymous function expression is created, which contains the module's own private variables and functions; the execution result of this function expression returns an object, which contains the public interface exposed by the module to the user. There are many specific forms of code modularity. For example, in some commonly used JavaScript libraries, immediate execution functions similar to the following examples are usually used:
(function(){ var _name = ""; var root = this; var person = { getName: function(){ return _name; }, setName: function(newname){ _name = newname; } }; root.person = person; }.call(this)); person.setName("John"); person.getName(); //"John"This method directly uses the object containing the module's public interface as an attribute of the global object, so that the attribute of the global object can be used elsewhere.
The above cliché JavaScript function expressions are all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.