// 将匿名函数赋值给 myFunc
const myFunc = function(param1, param2, ...) {
// Statements using param1, param2, ...
};
// 调用匿名函数
// param1 value is set to arg1, param2 to arg2, ...
myFunc(arg1, arg2, ...);
另一种方法
// Assignment of an anonymous function to the myFunc variable
const myFunc = (param1, param2, ...) => {
// Statements using param1, param2, ...
};
// Anonymous function call
// param1 value is set to arg1, param2 to arg2, ...
myFunc(arg1, arg2, ...);
举例
const hello = (name) => {
const message = `Hello, ${name}!`;
return message;
};
console.log(hello("William")); // "Hello, William!"
在某些特定情况下,箭头函数语法可以进一步简化:
- 当函数体中只有一条语句时,所有内容都可以写在同一行而不用花括号。该
return
语句被省略和隐含。 - 当函数只接受一个参数时,可以省略它周围的括号。
// Minimalist to the max
const hello = name => `Hello, ${name}!`;
console.log(hello("Kate")); // "Hello, Kate!"
// Say hello to the user
const sayHello = (firstName, lastName) => `Hello, ${firstName} ${lastName}!`;
// Alternative solution using a function declaration
/* function sayHello(firstName, lastName) {
return `Hello, ${firstName} ${lastName}!`;
} */
const firstName = prompt("Enter your first name:");
const lastName = prompt("Enter your last name:");
console.log(sayHello(firstName, lastName));