通过声明
通过关键词 function 定义 ,这是最早也是最经典的function定义方式。
function hello (firstname) {
console.log(`Hello ${firstname}`);
}
这个函数有一个名称 “hello”, 所以我们称这个函数为命名函数。
通过表达式
这是比较现代化的定义方式了。这种定义方式也说明了函数也是对象,因此可以把函数赋值给变量。
const hello = function (firstname) {
console.log(`Hello ${firstname}`);
};
仔细看,你会发现这个函数是没有名称的,因此它是匿名函数。
- 它在创建时,没有名称 (形如 “function (…) { … }”)。
- 即便我们把这个函数赋值给一个名称为hello的变量 , 它依然是一个匿名函数。
注意 : 这既然是一个赋值语句,那么在结尾处有分号就很自然了。 就像其他普通的赋值语句一样: const pi = 3.14; 。
通过箭头语法
箭头语法是ES6中出新的新语法,可以用在通过表达式定义函数的情境中:
- 去除关键词 function .
- 添加箭头符号 => 到参数右侧的位置.
const hello = (firstname) => {
console.log(`Hello ${firstname}`);
};
这种写法比叫简洁明了。如果满足以下情况写法可以更简单:
- 当只有一个参数时,参数外面可以不要圆括号。
- 当函数体内只有一行代码时,函数体可以不需要花括号"{ … }"包裹 。
- 当函数体内只有一行代码时,关键词return 可以省略。
以下对函数的三种定义方式是一个意思:
const hello1 = function (firstname) {
return `Hello ${firstname}`;
};
const hello2 = (firstname) => {
return `Hello ${firstname}`;
};
const hello3 = firstname => `Hello ${firstname}`;
下面我们用数组的.map()方法的callback调用,来体会以上三种定义函数的方式。
const test = [1, 2, 3];
function doubler (x) {
return x * 2;
}
test.map(doubler); // [2, 4, 6]
test.map(function (x) { return x * 2; }); // [2, 4, 6]
test.map((x) => { return x * 2; }); // [2, 4, 6]
test.map(x => x * 2); // [2, 4, 6]