javascript 中的函数可以重复使用,用法如下:函数声明:使用 function 关键字声明,接收参数并返回结果。函数表达式:使用 const 声明,接收参数并使用箭头符号 (=>) 返回结果。自调用函数:使用立即调用函数表达式 (iife) 声明,在定义时立即执行。类方法:在类定义中声明,通常用于对象的方法。
JavaScript 中的函数
JavaScript 中的函数是一种代码块,可以重复使用,并且可以传递参数和返回结果。
用法
声明函数
有四种方法可以声明函数:
-
函数声明:
function 函数名(参数) { 代码块 }
-
函数表达式:
const 函数名 = (参数) => { 代码块 }
-
自调用函数:
(function() { 代码块 })()
-
类方法:
class 类名 { 方法名(参数) { 代码块 } }
调用函数
调用函数只需使用其名称,后跟括号内的任何参数:
<code class="javascript">函数名(参数1, 参数2);
参数
函数可以接收参数,这些参数在函数体内作为变量使用。
返回值
函数可以使用 return
关键字返回一个值。
示例
函数声明:
<code class="javascript">function sayHello(name) {
return `Hello, ${name}!`;
}
const greeting = sayHello("Bob");
console.log(greeting); // 输出:"Hello, Bob!"
函数表达式:
<code class="javascript">const multiply = (a, b) => {
return a * b;
};
const product = multiply(10, 5);
console.log(product); // 输出:50
自调用函数:
<code class="javascript">(function() {
console.log("立即执行!");
})();
// 输出:"立即执行!"
类方法:
<code class="javascript">class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, my name is ${this.name}!`);
}
}
const person = new Person("Alice");
person.greet(); // 输出:"Hello, my name is Alice!"