1、实例
// 1.箭头函数例子function add(a, b) { return a + b;}// 1.使用箭头函数表达上面的函数let add1 = (a, b) => { return a + b;}// 2.简写方式: 函数体只有一行时let add2 = (a, b) => a + b;// 3.参数只有一个,小括号可以省略function squart(num) { return num * num;}// 简写 let squart2 = num => num * num;
2、箭头函数的使用场景
// 1.2 箭头函数常见使用场景// 1. 回调函数const list = [1, 2, 3, 4, 5, 6];list.forEach(function(item, index) { // todo});list.forEach((item, index) => { // todo});list.forEach(item => { // todo});// 2.setTimoutsetTimeout(() => { // todo}, 1000)// 3.promiselet promiseObj = new Promise((resolve, reject) => { // todo})promiseObj.then(res => { // todo}).catch(err => { // todo});
3、箭头函数的this指向
// 箭头函数this的指向let obj = { getList() { console.log('this的指向', this);//obj setTimeout(()=> { console.log('setTimout', this);//window }, 1000); }}obj.getList();