我们今天来聊一聊箭头函数和普通函数的区别
一、定义语法
我们想要了解箭头函数,我们就得先知道它咋玩
函数定义
// 这是普通函数定义的方式
function fn(){
}
// 箭头函数定义
let fn = ()=>{
}
形参定义
// 箭头函数只有一个形参时,可以省略掉小括号
let fn = num => {
}
// 有多个 形参 或 没有形参 的时候需要加上小括号
let fn2 = (num1, num2){
}
返回值
// 我们现在有一个相加函数 sum
let sum = (num1, num2) => {
return num1 + num2;
}
// 在箭头函数中只有一行代码,且需要返回的时候 可以省略 return 和大括号
let sum = (num1, num2) => num1 + num2;
箭头函数的简洁化案例
上面我们讲述了箭头函数在某些情况下有省略写法,我们来看看 实例
/* forEach 遍历*/
// 使用es5
let list = [1, 2, 3, 4, 5, 6]
list.forEach(function(item){
console.log(item)
})
// 箭头函数 一行搞定
list.forEach(item => console.log(item))
// 数组中的map, reduce, some, filter, find, findIndex等需要传入回调的方法都可以使用箭头函数的方式来传参
二、箭头函数细节
了解完箭头函数的用法过后,我们来看看箭头函数的一些细节
(1) 箭头函数中没有arguments
let fn = () => console.log(arguments)
fn() // Uncaught ReferenceError: arguments is not defined
(2) 箭头函数的this不能通过apply、call、bind方法更改( this永远不变 )
let obj = {}
let fn = () => {
console.log(this)
}
fn.call(obj) // => window
fn.apply(obj) // => window
fn.bind(obj)()// => window
(3) 箭头函数中的this来自上下文
案例一:事件监听的时候绑定函数
let box = document.querySelector('.box');
// 使用普通函数
box.onclick = function () {
console.log(this) // this => box元素
}
// 使用箭头函数
box.onclick = () => {
console.log(this) // this => window
}
普通函数绑定事件,this 指向 元素本身
箭头函数中的 this 指向 window
因为我们定义函数时的上下文环境是全局,所以他的this是就指向了window,可能大家还有所疑惑,我们再来看一个例子
class Person {
constructor(name) {
this.uname = name
}
showName() {
// 在定时器内部回调我们的函数的时候,
// 会将函数中的this改成 window 我们在以前就只能通过变量
// that 来临时存储 this 对象从而保证回调函数中能拿到实例对象
let that = this
setTimeout(function () {
// console.log(this.uname) // => undefined
console.log(that.uname) // => 张三
}, 1000)
}
}
new Person('张三').showName()
我们将上述代码中的函数改成箭头函数,输出的结果就是 张三 再一次证明了箭头函数的this是不能更改的
class Person {
constructor(name) {
this.uname = name
}
showName() {
setTimeout(() => {
console.log(this.uname) // => 张三
}, 1000)
}
}
new Person('张三').showName()
(4) 箭头函数没有prototype
这个很好理解, 相信大家如果知道es5定义类的方法的应该就知道prototype这个属性