ES6 允许使用“箭头”(=>)定义函数。但箭头函数没有自己的 this
、arguments
、super
、new.target
、prototype
。
- 函数体内的
this
对象,就是定义时所在的对象,而不是使用时所在的对象。function foo() { setTimeout(() => { console.log('id:', this.id); }, 100); } var id = 21; foo.call({ id: 42 }); // id: 42 复制代码
- 不可以当作构造函数,即,不可以使用
new
命令,亦即,没有new.target
、prototype
。const f = () => {} const c = new f() // Uncaught TypeError: f is not a constructor console.log(f.prototype) // undefined // about new.target // new.target 返回,使用 new 方法调用类时的类的名称;子类继承父类时,new.target 会返回子类。 class A { constructor(){ console.log(new.target.name) } } class B extends A { constructor(){ super() } } new A() // A new B() // B 复制代码
- 不可以使用
arguments
对象,该对象在函数体内不存在。如果要用,可以用rest
参数代替。const f1 = () => { console.log(arguments) } f1([1, 2, 3]) // Uncaught ReferenceError: arguments is not defined const f2 = (...rest) => {console.log(rest)} f2(1, 2, 3) // (3) [1, 2, 3] 复制代码
- 不可以使用
yield
命令,因此箭头函数不能用作Generator
函数。