箭头函数总结
// 优点:
// 1. 更加简短的函数(匿名函数)
// 2. 更加直观的作用域和this绑定(不绑定this)
为什么用箭头函数
// 简短
// no this
// 箭头函数并没有它自己的执行上下,实际上,这就意味着代码中的this和arguments都是继承它的父函数。
const name = 'windowName'
const obj = {
name: 'morning',
addFn: function() {
return () => {
console.log(this.name);
// morning
console.log('this',this);
// this { name: 'morning', addFn: [Function: addFn] }
return this
}
}
}
const fn = obj.addFn()
// fn()
// 不绑定arguments
function foo(n,m) {
const f = () => {
console.log(arguments);
// [Arguments] { '0': 1, '1': 2 }
console.log(arguments[0]); // 1
}
return f()
}
// foo(1,2)
怎么用
// 用于优化代码:
// 1. 使用map时
// 2. 使用forEach 代替 for 时
// 3. promise and promise链时
// 4. 用于封装的对象转换
什么时候不使用
// 1. 使用new时
Foo = () => {};
// foo = new Foo()
// TypeError: Foo is not a constructor
// 箭头函数不能用作构造器
// 2. 使用prototype时
// console.log(Foo.prototype);
// undefined
// 箭头函数没有prototype属性
// 3. yield 生成器
// 4. 调试代码时
常见错误
// 返回对象字面量
const fn1 = () => {a:1};
console.log(fn1()); // undefined
const fn2 = () => ({a:1});
console.log(fn2()); // { a: 1 }
箭头函数用作闭包
// 箭头函数用作闭包
// 标准闭包
function A() {
let x = 1
return function B() {
return x + 1
}
}
const fn3 = A()
console.log(fn3()); // 2
// 箭头函数闭包
const BiBao = (i = 1) => {
return (() => {
return (i + 1)
})
};
// const BiBao1 = (i=1) => () => (i+1)
const fn4 = BiBao()
console.log('闭包',fn4()); // 闭包 2
623

被折叠的 条评论
为什么被折叠?



