ES6入门:箭头函数
一、箭头函数
// () => {} 相当于一个匿名函数,无法直接起名字
const add = (x, y) => {
return x + y;
};
console.log(add(1, 1)); //2
1).结构 :const/let 函数名 = 参数 => 函数体
2).将一般函数改写成箭头函数:
function add() {} //声明形式
const add = function () {}; //声明形式->函数表达式形式
const add = () => {}; //函数表达式形式->箭头函数
二、箭头函数的注意事项
1、单个参数
1)单个参数可以省略圆括号
const add = x => {
return x + 1;
};
console.log(add(1)); //2
2)无参数或多个参数不能省略圆括号
const add = () => { //无参数
return 1 + 1;
};
console.log(add(1));
const add = (x, y) => { //多个参数
return x + y;
};
console.log(add(1, 1));
2、单行函数体
单行函数体可以同时省略 {}
和 return
;多行函数体不能再化简了
//const add = (x, y) => {
// return x + y;
//};
const add = (x, y) => x + y;
console.log(add(1, 1));
3、单行对象
如果箭头函数返回单行对象,可以在 {} 外面加上 (),让浏览器不再认为那是函数体的花括号
//const add = (x, y) =>{
// return{
// value: x + y
// };
// };
const add = (x, y) => ({
value: x + y
});
console.log(add(1, 1)); //2
关于箭头函数、非箭头函数的this指向参考即可