1. 箭头函数的特性
箭头函数是ES6之后增加的一种编写函数的方法,并且它比函数表达式要更加简洁:
-
箭头函数不会绑定
this、arguments属性 -
箭头函数不能作为构造函数来使用(不能和new一起来使用,会抛出错误)
2. 箭头函数的写法
-
基本写法
// 1.之前的方式 function foo1() {} var foo2 = function(name, age) { console.log("函数体代码", this, arguments) console.log(name, age) } // 2.箭头函数完整写法 var foo3 = (name, age) => { console.log("箭头函数的函数体") console.log(name, age) } // 3.箭头函数的练习 // 3.1. forEach var names = ["abc", "cba", "nba"] names.forEach((item, index, arr) => { console.log(item, index, arr) }) // 3.2. setTimeout setTimeout(() => { console.log("setTimeout") }, 3000) -
优化写法
- 只有一个参数时, 可以省略()
- 只有一行代码时, 可以省略{}
- 只要一行代码时, 表达式的返回值会作为箭头函数默认返回值, 所以可以省略
return - 如果箭头函数默认返回的是对象, 在省略{}的时候, 对象必须使用()包裹
() => ({name: "kobe"})
var names = ["abc", "cba", "nba"]
var nums = [20, 30, 11, 15, 111]
// 1.优化一: 如果箭头函数只有一个参数, 那么()可以省略
// names.forEach(item => {
// console.log(item)
// })
// var newNums = nums.filter(item => {
// return item % 2 === 0
// })
// 2.优化二: 如果函数体中只有一行执行代码, 那么{}可以省略
// names.forEach(item => console.log(item))
// 一行代码中不能带return关键字, 如果省略, 需要带return一起省略(下一条规则)
// var newNums = nums.filter(item => {
// return item % 2 === 0
// })
// 3.优化三: 只有一行代码时, 这行代码的表达式结果会作为函数的返回值默认返回的
// var newNums = nums.filter(item => item % 2 === 0)
// var newNums = nums.filter(item => item % 2 === 0)
// 4.优化四: 如果默认返回值是一个对象, 那么这个对象必须加()
// 注意: 在react中我会经常使用 redux
// var arrFn = () => ["abc", "cba"]
// var arrFn = () => {} // 注意: 这里是{}执行体
// var arrFn = () => ({ name: "why" })
// console.log(arrFn())
// 箭头函数实现nums的所有偶数平方的和
var nums = [20, 30, 11, 15, 111]
var result = nums.filter(item => item % 2 === 0)
.map(item => item * item)
.reduce((prevValue, item) => prevValue + item)
console.log(result)
3. 箭头函数中的this
- 箭头函数是没有绑定this
- this的查找规则:
- 去上层作用域中查找this
- 直到找到全局this
var bar = () => {
console.log("bar:", this)
}
bar() // window
// 通过apply调用时, 也是没有this, 找到上层作用域的this
bar.apply("aaaa") // window
var obj1 = {
name: "obj1",
foo: function() {
var bar = () => {
console.log("bar:", this)
}
return bar
}
}
// 返回 bar 函数
var fn1 = obj1.foo()
fn1.apply("bbb") // 不绑定this,去上层查找,指向obj1
var obj2 = {
name: "obj2",
foo: () => {
var bar = () => {
console.log("bar:", this)
}
return bar
}
}
// 返回 bar 函数
var fn2 = obj2.foo()
fn2.apply("bbb") // 不绑定this,去上层查找,依次查到全局window
4. 箭头函数this应用
- 模拟网络请求
- 回调:函数传来传去
// 网络请求的工具函数
function request(url, callbackFn) {
var results = ["abc", "cba", "nba"]
callbackFn(results) // 独立函数调用
}
// 实际操作的位置(业务)
var obj = {
names: [],
network: function() {
// 1.早期写法
// var _this = this
// request("/names", function(res) {
// _this.names = [].concat(res)
// })
// 2.箭头函数写法
request("/names", (res) => {
this.names = [].concat(res)
})
}
}
obj.network()
console.log(obj) // {names: Array(3), network: ƒ}