Chapter 4 Javascript functions

A function is composed of a series of subroutines (a collection of statements), which can be called by external programs. After passing parameters to the function, the function can return a certain value. Note that the function in JavaScript is also an object. When you use typeof to check a function object, function will be returned.

4.1 definition of function

In Javascript, a function is defined by the keyword function, the function name plus a set of parameters, and a piece of code to be executed in braces. Basic syntax:

function functionNeme([parameter 1,parameter 2,...]){
	statements;
	[return expression;]
}

Parameter Description:
functionName: required to specify the function name. Remain unique and case sensitive.
Parameter: optional, used to specify the parameter list. When there are multiple parameters, separated by commas, a function can have up to 255 parameters.
statement: required to specify the function body. That is, the code block that implements the function.
Expression: optional, used to return the function value. Can be any expression / variable or constant.

For example, define a function account() for calculating the amount of goods, and the return value is the calculated amount of goods.

 function account(price, num) {

	 var sum = price * num; // Calculated amount
	
	 return sum; // Return value

 }

4.2 function call

After a function is defined, it will not be executed automatically. To execute a function, you need to call a statement at a specific location. The call statement includes name, parameter specific value, etc.

4.2.1 simple call of function

The function definition statement is usually placed in the segment of the HTML file, and the function call statement is usually placed in the segment. If function is called before function definition, execution will be wrong.
Function definition and call instance:

<!DOCTYPE html>

<html>

 <head>

 <meta charset="utf-8">

 <title>Test code</title>

 <script type="text/javascript">

 function account(price, num) { // Define function

 var sum = price * num; // Calculated amount

 alert(sum); // Output results

 }

 </script>

 </head>

  

 <body>

 <script type="text/javascript">

	 account(20, 100); // Call function

 </script>

 </body>

</html>

Execution results:

The parameters of a function are divided into formal parameters (formal parameters) and actual parameters (actual parameters). The formal parameters are the parameters given by the function, representing the position and type of the function. The system does not allocate corresponding storage space for the formal parameters. When calling a function, the parameters passed to the function are called actual parameters. The actual parameters are usually allocated memory and given actual data before calling the function. During the execution of the function, the actual parameters participate in the operation of the function. price and num in the above example are formal parameters.

4.2.2 invokes function in event response

When a user clicks a button or selects a check box, an event will be triggered. The behavior of writing a program to respond to the event is called response event. In Javascript, the process of responding to events is completed by associating functions with events.

For example, when a user clicks a button, the corresponding function is executed.

<!DOCTYPE html>

<html>

  

<head>

 <meta charset="utf-8">

 <title>Test code</title>

 <script type="text/javascript">

 function test() { // Define function

 alert("test") // Return value

 }

 </script>

</head>

  

<body>

 <form action="" method="get" name="from1">

 <input type="button" value="Submit" onclick="test();">

 <!--The function is called when the button event is triggered-->

 </form>

  

</body>

  

</html>

Execution results:

4.2.3 calling functions through hyperlinks

Use the format of "javascript: function name ()" in the href attribute in the < a > tag to call the function. When the user clicks the hyperlink, the related function will be executed.

<!DOCTYPE html>

<html>

  

<head>

 <meta charset="utf-8">

 <title>Test code</title>

 <script type="text/javascript">

 function test() { // Define function

 alert("test") // Return value

 }

 </script>

</head>

  

<body>

 <a href="javascript:test();">Alexhesz</a>

</body>

  

</html>

Execution results:

4.3 nested functions

The so-called nested function is to define another function inside the function. The advantage of this definition is that the internal function can easily obtain the parameters of the external function and the global variables of the function. Nested functions are very powerful in JavaScript, but you need to be careful when using them, because they will reduce the readability of the program.

Syntax format:

<script type="text/javascript">
var outter = 10;
function functionName([parameter 1,parameter 2,...]){
	function innerFunction(){
			somestatements;
	}
}
</script>

Parameter Description:

functionName: external function name;
innerFunction: name of the nested function.

Instance to obtain the sum of global variables and external function parameters in nested functions.

<!DOCTYPE html>

<html>

  

<head>

 <meta charset="utf-8">

 <title>Test code</title>

 <script type="text/javascript">

 var num = 10; // Define global variables

 function add(num1, num2) { // Define external functions

 function innerAdd() { // Define internal functions

 alert("The parameters and are:" + (num1 + num2 + num));

 }

 return innerAdd();

 }

 </script>

</head>

  

<body>

 <script type="text/javascript">

 add(10, 10) // Call function

 </script>

</body>

  

</html>

Execution results:

4.4 recursive function

The so-called recursive function is that a function calls itself in its own function body. Be careful when using recursive function. Improper handling will make Chen drum type enter an dead cycle. Recursive functions can be used to deal with some special cases, such as factorial problems.

Syntax format:

<script type="text/javascript">
var outter = 10;
function funtionName(parameter 1){
		functionName(parameter 2)
}
</script>

Example: application of recursive function

<!DOCTYPE html>

<html>

  

<head>

 <meta charset="utf-8">

 <title>Test code</title>

 <script type="text/javascript">

 function f(num) { // Define recursive function

 if (num <= 1) {

 return 1;

 } else {

 return f(num - 1) * num;

 }

 }

 </script>

</head>

  

<body>

 <script type="text/javascript">

 alert("5!The results are:" + f(5)) // Call function output

 </script>

</body>

  

</html>

Execution results:

Two necessary conditions are required when defining a recursive function:

  • Include an end return condition. For example, if the "if (Num < 1)" statement in the instance meets the conditions, execute "return 1;" Statement, no longer return.
  • Includes a recursive call statement. For example, "return f(num-1)*num;" Statement, used to call recursive functions.

4.5 built in functions in JavaScript

4.5.1 parseInt() function

This function mainly converts the string with the first digit into a number. If the string does not start with a number, NaN will be returned.

Syntax:

parseInt(StringNum,[n])

StringNum: a string that needs to be converted to an integer.

n: A number between 2 and 36 is provided to represent the hexadecimal number of the saved number. This argument is not required in the function.

Float() function 5.4

This function mainly converts the string whose first digit is a number into a floating-point number. If the string does not start with a number, NaN will be returned.

Syntax:

parseFloat(StringNum)

StringNum: a string that needs to be converted to floating point.

4.5.3 isNaN() function

This function is mainly used to check whether a value is NaN.

Syntax:

isNaN(Num)

Num: number to be verified.

Note: if the parameter Num is NaN, the return value of the function is true; If the parameter Num is not NaN, the return value of the function is false.

4.5.4 isfinish() function

This function is mainly used to check whether an expression is infinite.

Syntax:

isFinite(Num)

Num: number to be verified.

Note: if the parameter Num is infinite, the return value of the function is true; If the parameter Num is not infinite, the return value of the function is false.

4.5.5 encodeURI() function

This function is mainly used to return the encoded result of a URI string.

Syntax:

encodeURI(url)

url: a string that needs to be converted to a network resource address.

Note: both URI and URL can represent the network resource address. URI has a wider range than URL, but in general, URI and URL can be the same. The encodeURI() function only escapes meaningful characters in the string. For example, convert spaces in a string to "% 20".

4.5.6 decodeURI() function

This function is mainly used to decode the string encoded as URI into the original string and return it.

Syntax:

decodeURI(url)

url: the address of the network resource to be decoded.

Note: this function can convert the network resource address transcoded by encodeURI() into a string and return it, that is, the decodeURI() function is the reverse operation of encodeURI() function.

4.6 Function() constructor and function direct quantity

In addition to using basic function statements to define functions, you can also use Function() functions and function literals to define functions. There is an important difference between the two.

  • The constructor Function() allows you to dynamically create and compile JavaScript code at run time, while the function directness is a static part of the program structure, just like a function statement.
  • Each time the constructor Function() is called, the function body is parsed and a new function object is created. If the call to the constructor occurs in a loop or in a frequently called function, this method will be very inefficient. Whether the function direct quantity appears in the loop body or nested function, it will not be recompiled every time it is called, nor will a new function object be created every time it is encountered.
  • The function created by Function() does not use a static scope. Instead, the function is always compiled as a top-level function.

Example Screen mouse and keyboard related events through custom functions.

<!DOCTYPE html>

<html>

  

<head>

 <meta charset="utf-8">

 <title>Test code</title>

 <script type="text/javascript">

 function maskingKeyboard() { // Define function

 if (event.KeyCode == 8) { // Determine whether it is a Backspace key

 event.KeyCode = 0;

 event.returnValue = false;

 alert("The current page is not allowed Backspace Key!!!");

 }

 if (event.KeyCode == 13) { // Determine whether to Enter

 event.KeyCode = 0;

 event.returnValue = false;

 alert("The current page is not allowed Enter Key!!!");

 }

 if (event.KeyCode == 116) { // Determine whether it is F5 key

 event.KeyCode = 0;

 event.returnValue = false;

 alert("The current page is not allowed F5 Key!!!");

 }

 // Judge whether it is A lt + direction key direction key < -- or direction key -- >

 if ((event.altKey) && ((window.KeyCode == 37) || (window.event.KeyCode == 39))) {

 event.returnValue = false;

 alert("The current page is not allowed Alt+Direction key direction key<-Or direction key——>");

 }

 if ((event.ctrlKey) && (event.KeyCode == 78)) { // Determine whether it is Ctrl+N

 event.returnValue = false;

 alert("The current page is not allowed Ctrl+N New window!!!");

 }

 if ((event.shiftKey) && (event.KeyCode == 121)) { // Judge whether it is Shift+F10

 event.returnValue = false;

 alert("The current page is not allowed Shift+F10 Key!!!");

 }

 }

 </script>

</head>

  

<body onkeydown="maskingKeyboard()">

 <!--Call function maskingKeyboard()-->

 <p>Once upon a time, the sea is hard to water,</p>

 <p>Except that Wushan is not a cloud.</p>

</body>

  

</html>

Keywords: Javascript Front-end

Added by kaser on Sun, 02 Jan 2022 16:22:56 +0200