箭头函数的特征
箭头函数的特征
-
this是静态的,this 始终指向函数声明时所在作用域下的this值。
-
如果是构造函数不能使用构造函数,会抛异常(Person is not a constructor)例如
let Person = (name, age)=> { this.name = name; this.age = age } let p1 = new Person('张三', 20); console.log(p1); // Person is not a constructor
-
不能使用 argument 变量(存储实参),会抛异常(arguments is not defined)。
let fn = () => { console.log(arguments); // arguments is not defined }
-
箭头函数的简写
-
省略小括号,当形参有且只有一个参数的时候。
let add = n => { return n + n; }
-
省略花括号,当代码体只有一条语句的时候,此时
return
必须省略。let pow = n => n*n
-
箭头函数的应用场景
- 箭头函数适合于
this
无关的回调。(定时器、数组方法回调) - 箭头函数不适合
this
有关的回调。(事件回调,对象的方法)