- 箭头函数就是先把 function 删掉,然后,在 () 和 { } 之间,添加一个 =>
var fn = function() {
console.log("1111")
}
var fn = () => {
console.log("1111")
}
- 箭头函数本质就是一个匿名函数,箭头函数内部的this永远和箭头函数外部的this保持一致
document.getElementById('btn').onclick = function () {
setTimeout(function () {
var _this = this
_this.style.backgroundColor = 'red'
}, 1000)
}
document.getElementById('btn').onclick = function() {
setTimeout(() => {
this.style.backgroundColor = 'red'
}, 1000)
}
- 最标准的箭头函数格式是 ( 参数列表 ) => { 函数体 }
- 如果 箭头函数左侧的 形参列表中,只有一个 形参,那么,( ) 可以省略 ( x ) => { console.log(x) } 可以改造成 x => { console.log(x) }
- 如果 箭头函数右侧的 函数体中,只有一行代码,那么, { } 可以省略 (x, y) => {console.log(x + y)} 可以改造成 (x, y) => console.log(x + y)
- 如果箭头函数 左侧 只有一个形参,右侧只有一行代码,那么, 左侧的 () 和 右侧的 {} 都可以省略 ( x ) => { console.log(x) } 可以改造成 x => console.log(x)
- 如果我们省略了 右侧的 { }, 那么,默认就会把 右侧函数体中的代码执行结果,返回出去 (x, y) => { return x + y } 可以简写成 (x, y) => x + y