箭头函数特点:简化代码写法
- 箭头函数没有"function"关键字
- 小括号和大括号之前用箭头"=>"隔开
- 如果形参只有一个可以省略小括号
- 如果没有return 可以省略大括号
- 如果返回值是一个对象,需要将返回值用小括号括起来
//以前的写法
var fn = function(a){
return a;
}
console.log(fn(1));
// 1
//ES6 写法
let fn = a=>a;
console.log(fn(1));
// 1
//在一个函数中嵌套了另一个函数
//以前的写法
function a(c){
function b(d){
return a+b;
}
}
// ES6写法
let a = c=>d=>c+d;
console.log(a(2)(3));
// 5
//在一个函数中嵌套了另一个函数,返回一个对象
//以前的写法
function a(c){
function b(d){
return {sum:a+b};
}
}
// ES6写法
let a = c=>d=>({sum:c+d});
console.log(a(2)(3));
// { sum: 5 }
箭头函数特点:this指向
this指向的问题解决方法
- 在调用this的前一个作用域通过 let that = this 解决
- 通过bind的方式给当前作用域绑定为上一层作用域的this,(没有异步的情况下也可以使用call apply)
- 箭头函数
let obj = {
a:1,
b:function(){
let that = this
setTimeout(function(){
console.log(that) //window
},1000)
}
}
obj.b();
let obj = {
a:1,
b:function(){
setTimeout(function(){
console.log(this) //window
}.bind(this),1000)
}.bind(this)
}
obj.b();
let obj = {
a:1,
b:()=>{
setTimeout(()=>{
console.log(this) //window
},1000)
}
}
obj.b();
- 箭头函数内没有this,每次取值this 都是在箭头函数的上一层作用域进行查找,如果上一层也没有this就继续向上找
let obj = {
a:1,
b:()=>{
setTimeout(()=>{
console.log(this); //window
},100)
}
}
obj.b();
例子
- 对象的大括号不算一个作用域
- let 声明的变量不会挂载到window上
let a =1;
let obj = {
a:2,
b:()=>{
console.log(this); //window
console.log(this.a); // undefined
console.log(a); // 1
}
}
obj.b();
var a =1;
let obj = {
a:2,
b:()=>{
console.log(this); //window
console.log(this.a); // 1
console.log(a); // 1
}
}
obj.b();
箭头函数 多参数传递(剩余运算符)
- 箭头函数没有 arguments
- ... 剩余运算符可以将最后面的形参放到一个数组中去(接收参数时只能放到最后一个位置)
let fn = (a,...arr)=>{
console.log(arr)
}
fn('sssss',1,3,2.33,22,345)
// [ 1, 3, 2.33, 22, 345 ]
个人博客cometang:www.gotang.cn
常见问题FAQ
- 免费下载或者VIP会员专享资源能否直接商用?
- 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
- 提示下载完但解压或打开不了?
- 找不到素材资源介绍文章里的示例图片?
- 模板不会安装或需要功能定制以及二次开发?
发表评论
还没有评论,快来抢沙发吧!