描述
箭头的函数的主要两个作用
- 更简短的函数,方便一些高阶函数的使用
- 不绑定
this
箭头函数特性
- 箭头函数不会创建自己的
this
,它只会从自己的作用域链的上一层继承this
- 没有
arguments
对象,用rest (拓展运算符)
替代 - 不能生成 generator 函数,和使用
yield
关键字 - 不能作为构造函数来使用
bind
apply
call
,使用这些则会忽略第一个参数 - 不能用作构造函数
书写形式
const fn = (param1, param2, …, paramN) => { statements }
当只有一个可选参数时,()
是可选的
const fn = param1 => { statements }
当函数执行的结果可以直接 return
时
const fn = param1 => param1.toString()
当然我们也可以用表达式来简化 return
const fn1 = param1 => ({ params: param1.toString() }) // 表示 return 一个对象 { params: param1.toString() }
const fn2 = param1 => (params += 10, param1) // () 表示一个表达式,返回最后一个表达式内容
参数 rest
写法,表示收集余下参数成一个数组
只能作为最后一个参数
const fn = (params, ...otherParams) => { statements }
不同的书写形式
let arrowFunction;
arrowFunction = () => { }
arrowFunction = (params) => { }
arrowFunction = (params1, params2) => { }
arrowFunction = (...args) => { }
arrowFunction = (params1, ...args) => { }
arrowFunction = params => { }
arrowFunction = params => params
arrowFunction = params => Boolean(params)
arrowFunction = params => params === undefined ? true : false
arrowFunction = (numberA, numberB) => numberA + numberB
arrowFunction = (a, b) => [a, b]
注意:当要简写使其返回对象的时候需要使用 ()
包起来使其成为一个表达式
否则 `{}` 默认会被当成函数主体
let foo = (a, b) => ({a, b})
可以作为立即使用函数
(() => { console.log(1) })() // 1
箭头函数没有自己的 this
argument
constructor
因此他在哪里被定义就指向哪里的this
且不会被改变
function foo() {
var self = this
const fn = () => {
console.log(this === self); // true
}
fn()
}
foo()
箭头函数使用 bind
apply
call
var name = 'window'
const obj = { name: 'obj' }
const fn = func => console.log(this.name, func)
const bindFn = fn.bind(obj)
bindFn('bind') // window bind
fn.apply(obj,['apply']) // window apply
fn.call(obj,'call') // window call
没有自己的 arguments
function normalFunction() {
const arg = arguments
const arrowFunction = (...args) => {
console.log(arg === arguments) // true
// 所以一般用 ...args 来收集参数
}
arrowFunction()
}
normalFunction()
无法使用 new
关键词
var Foo = () => {};
var foo = new Foo(); // TypeError: Foo is not a constructor - 报错
没有 prototype
属性
var Foo = () => {};
console.log(Foo.prototype); // undefined
解析顺序
let callback;
callback = callback || function () { }; // ok
/**
* 以下几种情况会报错
* Malformed arrow function parameter list
*/
callback = callback || () => { };
callback = callback || (params) => { };
callback = callback || (params1, params2) => { };
callback = callback || params => { };
callback = callback || params => params;
// 所以使用 () 包起来是他成为一个完整的表达式
callback = callback || (() => { }); // ok
使用闭包
var add = () => {
var num = 0
return () => {
num++
console.log(num)
}
}
var getNum = add()
getNum() // 1
getNum() // 2
使用递归
var fact = (x) => (x == 0 ? 1 : x * fact(x - 1));
fact(5); // 120
当作高阶函数的参数
var arr = [5, 6, 1, 2, 3, 7,]
arr.forEach(item => console.log(item))
arr.find(item => item > 5)
arr.sort((a, b) => a - b)