The function is defined by the keyword function. There are two methods to define the function: Function Definition expression and function declaration statement. The following exampleCodeIn the following two definitions:
//Function Definition expressionVaRSquare =Function(X ){ReturnX *X ;};//Function declaration statementFunctionSquare (x ){ReturnX *X ;};
Although function declaration statements and Function Definition expressions contain the same function name, they are still different. Like declaring a variable through var, the function in the Function Definition Statement is explicitly "advanced" to the top of the script or function. Therefore, they are visible throughout the script and function. If VaR is used, only the variable declaration is in advance-the initialization code of the variable is still in the original position. However, if you use a function declaration statement, the function name and function body are both in advance: All functions in the script and all nested functions in the function will be declared before other code in the current context. That is, you can call a JavaScript function before declaring it.
<! Doctype html > < Html Lang = "En-us" > < Head > < Meta Charset = "UTF-8" > < Title > JS-Function </ Title > </ Head > < Body > </ Body > </ Html > < Script Type = "Text/JavaScript" > Distance ( 0 , 0 , 3 , 4 ); // Function declaration statement-whatever the definition, it will be "advanced" to the top of the script or function. Function Distance (x1, Y1, X2, Y2 ){ VaR DX = X2 - X1; VaR Dy = Y2 - Y1; alert (math. SQRT (square (dx) + Square (dy )));}; // Function Definition expression-only the variable declaration is in advance, and the variable initialization code is still in the original position. Pay attention to the JS execution sequence. VaR Square = Function (X ){ Return X * X ;}; </ Script >
In the code above, because Square is a function definition expression and is defined at the end, the value of Square is undefined when the distance function is executed.
Solution:
1. Change the syntax of the Function Definition expression to that of the function declaration statement.
2. Write the function definition expression before the execution function (distance (0, 0, 3, 4.