箭头函数:
1、单行代码可加也可不加{ },若需写多行则添加{ };单行代码不加{ }的话,箭头函数自带返回值;
//单行不加{ }的话,箭头函数自带返回值;
const add = (a, b) => a+b
//多行则添加{ }
const add1 = (a, b) => {
a += 1;
return a + b;
};
console.log(add1(2, 2));
2、单行代码不需要返回值方法:
//行代码添加{ },以多行方式显示,则无返回值;
const pop = arr => {
arr.pop();
}
//箭头指向添加void,即可;结果不返回或返回undefined;
const pop = arr => void arr.pop();
console.log(pop([1, 2, 3]));
3、箭头函数和function的区别:
1)箭头函数没有arguments类数组,要用扩展运算符代替,使用…args去拿参数(组成数组)
const log = (...args) => {
console.log(args);
};
log(1, 2, 3);
2)箭头函数没有自己的this,箭头函数的this指向它被定义时自身所处环境的this,比如它在一个全局对象中的函数里被定义,那它的this就是window
const xiaoming = {
name: '小明',
say1: function() {
console.log(this);
},
say2: () => {
console.log(this);
}
}
xiaoming.say1();//输出了小明对象
xiaoming.say2();//输出window
3)箭头函数中的this指向的就是自身所处环境getAge的this,而getAge中的this指向的就是xiaoming,省略了普通函数方法中需要进行保留this指向的操作;如果是普通函数的话,要在这个getAge方法里的第一行定义var that=this来保留this的指向。
//普通函数需要进行保留this指向的操作
const xiaoming = {
name: 'xiaoming',
age: null,
getAge: function() {
let _this = this; //保留this的指向
// ...ajax
setTimeout(function() {
_this.age = 14;
console.log(_this);
}, 1000);
}
};
//箭头函数中的this指向的就是自身所处环境getAge的this,而getAge中的this指向的就是xiaoming
const xiaoming = {
name: 'xiaoming',
age: null,
getAge: function() {
// ...ajax
setTimeout(() => {
this.age = 14;
console.log(this);
}, 1000);
}
};
xiaoming.getAge();