The Function object in JavaScript is a Function. This article briefly introduces the three major uses of the Function in Script.
Function in JavaScript) object
Function objects in JavaScript are functions, and functions are used in three categories:
As a general logic code container;
As an object method;
As a constructor.
1. As a general logic code container
- functionmultiply(x,y){
- returnx*y;
- }
The multiply function encapsulates two-digit multiplication formulas:
- varproduct=multiply(128,128);//product=16384
-
You can create a function instance in three ways. The first type is declarative, that is, like declaring a variable, the anonymous function created using the function () {} identifier is directly assigned to the variable, using the variable as the name of the function used for calling:
- varmultiply=function(x,y){
- returnx*y;
- }
The second is the definition, that is, using the function keyword followed by the function name and () {} to directly define the name function. The first multiply function is created through the definition.
The third type is the constructor, that is, the constructor Function is called through the new operator to create a Function. This method is rarely used, so we will not introduce it.
Among the three methods for creating a function, there are still slight differences between declarative and defined types. For example, the function in the following Code adopts the declarative method:
- varexample=function(){
- return1;
- }
- example();
- varexample=function(){
- return2;
- }
- example();
-
The execution result is as follows:
- 1
- 2
If the definition is used, that is:
- functionexample(){
- return1;
- }
- example();
- functionexample(){
- return2;
- }
- example();
You will get another result:
- 2
- 2
That is, when a function with the same name is created using the definition, the created function will overwrite the previously created function. This difference is caused by the working mechanism of the JavaScript interpretation engine. Before executing any function call, the JavaScript interpretation engine registers a function created in a defined manner in the global scope, and then executes the function call in sequence. When registering a function, the previously defined function overrides the previously defined function. Therefore, no matter where the call statement is located, all the previously defined functions are executed. On the contrary, for declared functions, the JavaScript interpretation engine evaluates the variable just like any declared variable until the code that calls the variable is executed. Because JavaScript code is executed sequentially from top to bottom, when the first example () call is executed, the code of the example function defines the code first, and when the second example () is executed () during the call, the code of the example function becomes the Code defined later.