JavaScript 函数
基本概念
- 函数是一段可以重复使用的代码块。
- 函数可以接收输入,也就是参数。
- 函数可以执行特定任务,并返回结果。
基本语法
1 2 3 4
| function function_name(参数1, 参数2, 参数3) { return 返回值; }
|
- 参数可以不写,表示不传参。
return 是可选的,用来返回结果。
无参函数
1 2 3 4 5
| function hello() { console.log("Hello, World!"); }
hello();
|
有返回值的函数
1 2 3 4 5 6
| function hello_return() { return "Hello World! -- 返回值"; }
let message = hello_return(); console.log(message);
|
带参数的函数
1 2 3 4 5
| function hello_name(name) { return "Hello, " + name + "!"; }
console.log(hello_name("Alice"));
|
作用域
全局变量
- 在函数外部定义的变量通常是全局变量。
- 全局变量在大多数位置都可以访问。
局部变量
- 在函数内部定义的变量通常是局部变量。
- 局部变量只能在当前函数内部访问。
1 2 3 4 5 6 7
| let global_var = "全局变量";
function local_var_function() { let local_var = "局部变量"; console.log(global_var); console.log(local_var); }
|
课堂完整示例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JavaScript 函数</title> </head> <body> <script> function hello(){ console.log("Hello, World!"); }
hello();
function hello_return(){ return "Hello World! -- 返回值"; }
let message = hello_return(); console.log(message); console.log(hello_return());
function hello_name(name){ return "Hello, " + name + "!"; }
console.log(hello_name("Alice")); console.log(hello_name("Bob"));
let global_var = "全局变量"; function local_var_function(){ let local_var = "局部变量"; console.log(global_var); console.log(local_var); } local_var_function(); console.log(global_var); </script> </body> </html>
|
知识点总结
- 函数用于封装可重复使用的代码。
- 函数可以没有参数,也可以有参数。
- 函数可以没有返回值,也可以通过
return 返回结果。
- 作用域分为全局作用域和局部作用域。
复习表达
JavaScript 中函数是可重复使用的代码块,可以接收参数并返回结果。开发中函数常用于封装逻辑、减少重复代码。函数内部可以通过 return 返回值,变量作用域上通常分为全局变量和局部变量,局部变量一般只能在函数内部访问。