箭头函数中不存在this,arguments,new.target,如果使用,则使用的是函数外层的对应的this,arguments,new.target
箭头函数没有原型
箭头函数不能作用构造函数使用
何为箭头函数
let num = 0;setInterval(() => {console.log(this)num++;console.log(num)}, 1000);
如以上代码所示
箭头函数语法
(参数1, 参数2, …)=>{
//函数体
}
如果参数只有一个,可以省略小括号
示例如下
const numbers = [3, 7, 78, 3, 5, 345];const result = numbers.filter(num => num % 2 !== 0)console.log(result);
如果箭头函数只有一条返回语句,可以省略大括号,和return关键字
示例如下
const numbers = [3, 7, 78, 3, 5, 345];const result = numbers.reduce((a, b) => a + b)console.log(result);
完整示例
const numbers = [3, 7, 78, 3, 5, 345];const result = numbers.filter(num => num % 2 !== 0).map(num => num * 2).reduce((a, b) => a + b)console.log(result);
this指向
箭头函数的函数体中的this,取决去箭头函数定义的位置的this指向,而与如何调用无关
const func = ()=>{console.log(this) //window}func()let obj = {a:123,print(){prin = ()=>{console.log(this) // obj}prin()},}obj.print()
控制台打印如下
