箭头函数与普通函数(function
)的区别是什么?构造函数(function
)可以使用 new
生成实例,那么箭头函数可以吗?为什么?
箭头函数是普通函数的简写,可以更优雅的定义一个函数,和普通函数相比,有以下几点差异:
-
函数体内的
this
对象,就是定义时所在的对象,而不是使用时所在的对象; -
不可以使用
arguments
对象,该对象在函数体内不存在。如果要用,可以用rest
参数代替; -
不可以使用
yield
命令,因此箭头函数不能用作Generator
函数; -
不可以使用
new
命令,因为:-
没有自己的
this
,无法调用call、apply
; -
没有
prototype
属性,而new
命令在执行时需要将钩子函数的prototype
赋值给新的对象的__proto__
-
new 过程大致是这样的:
function newFunc(father, ...rest) {
var result = {};
result.__proto__ = father.prototype;
var result2 = father.apply(result, rest);
if (
(typeof result2 === 'object' || typeof result2 === 'function') &&
result2 !== null
) {
return result2;
}
return result;
}
Q.E.D.