1.ES6 允许使用“箭头”(=>)定义函数。
2.箭头函数的特点:保持上下文this指针一致。
3.箭头函数的写法:
//一般函数写法
var a = function (b) {
return c;
};
//箭头函数写法
let a = b => c;
4.如果箭头函数不需要参数或需要多个参数,用一个圆括号代表参数部分。
/*不带参函数*/
//一般函数写法
var f = function () { return 5 };
//箭头函数写法
var f = () => 5;
/*带多个参数函数*/
//一般函数写法
var sum = function(num1, num2) {
return num1 + num2;
};
//箭头函数写法
var sum = (num1, num2) => num1 + num2;
5.如果箭头函数的代码块有多条语句,则用大括号括起来,并且使用return语句返回。
var sum = (num1, num2) => { return num1 + num2; }
6.箭头函数里面的this指向当前对象
console.log(this);//指向window
let obj = {
sleep: function () {
console.log(this);//指向obj
setTimeout(() => {
console.log(this);//指向obj
}, 1000);
// setTimeout(function () {
// console.log(this);//指向wind
// }, 1000);
}
}
obj.sleep();
7.对象里的函数简写
let stu = {
eat: function () {
},
work() {
return {
}
}
}
8.函数参数设置默认值
let stus = (x = 2, y = 10) => {
console.log(x, y);//输出:2 10
}
stus();
console.log(stus.length);//输出:0,获取没有指定默认值的形参的个数值
9.箭头函数中参数对象的解构赋值
let fun = ({ a, b }) => {
console.log(a, b);
}
fun({ a: 1, b: 2 });
10.箭头函数作用域
let s1 = 10;
let fun2 = (x, y = s1) => {
console.log(s1);//输出:10
let s1 = 20;
console.log(y);//输出:10
}
fun2();
11.使用扩展运算符…获取函数多余参数(箭头函数中如果写arguments对象会报错,因为箭头函数上下文this保持一致 ,而window 中不含arguments)
let fun3 = function (...values) {
console.log(arguments);
console.log(values);
}
fun3(1, 2, 3, 4);
12.箭头函数嵌套:找最外层this
let fun5 = () => {
console.log(this);//输出:window
return () => {
console.log(this);
}
}
fun5();