箭头函数语法
基本语法
// 普通函数
const fn1 = function() {
console.log('普通函数')
}
fn1()
// 箭头函数
const fn2 = () => {
console.log('箭头函数')
}
fn2()
只有一个参数可以省略小括号
// 普通函数
const fn1 = function(x) {
return x + x
}
console.log(fn1(2)) // 4
// 箭头函数
const fn2 = x => {
return x + x
}
console.log(fn2(2)) // 4
如果函数只有一行代码,可以写到一行上,且无需写return直接返回值
两个形参不能省略括号
// 普通函数
const fn1 = function(x, y) {
return x + y
}
console.log(fn1(1, 2)) // 3
// 箭头函数
const fn2 = (x, y) => x + y
console.log(fn2(1, 3)) // 4
加括号的函数体返回对象字面量表达式
const fn = uname => ({ uname: uname })
console.log(fn('andy')) // {uname: 'andy'}
总结
-
箭头函数属于表达式函数,因此不存在函数提升
-
箭头函数只有一个参数时可以省略圆括号 ()
-
箭头函数函数体只有一行代码时可以省略花括号 {},并自动作为返回值被返回
-
加括号的函数体返回对象字面量表达式
箭头函数参数
-
普通函数有arguments 动态参数
-
箭头函数没有 arguments 动态参数,但是有 剩余参数 ..args
// 1. 利用箭头函数来求和
const getSum = (...arr) => {
let sum = 0
for (let i = 0; i < arr.length; i++) {
sum += arr[i]
}
return sum
}
const result = getSum(2, 3, 4)
console.log(result) // 9
箭头函数this
箭头函数不会创建自己的this,它只会从自己的作用域链的上一层沿用this
// 以前this的指向: 谁调用的这个函数,this 就指向谁
console.log(this) // window
// // 普通函数
function fn1 () {
console.log(this) // window
}
window.fn1()
// 对象方法里面的this
const obj = {
name: 'andy',
sayHi: function () {
console.log(this) // obj
}
}
obj.sayHi()
// 2. 箭头函数的this 是上一层作用域的this 指向
const fn2 = () => {
console.log(this) // window
}
fn2()
// 对象方法箭头函数 this
const obj2 = {
uname: 'andy',
sayHi: () => {
console.log(this) // this 指向谁? window
}
}
obj2.sayHi()
const obj3 = {
uname: 'andy',
sayHi: function () {
// console.log(this) // obj
let i = 10
const count = () => {
console.log(this) // obj
}
count()
}
}
obj3.sayHi()
在开发中【使用箭头函数前需要考虑函数中 this 的值】,事件回调函数使用箭头函数时,this 为全局的 window,因此DOM事件回调函数为了简便,还是不太推荐使用箭头函数