(1)写法不同,箭头函数更简洁
// 箭头函数
let fn = () => {console.log('haha')};
// 普通函数
let foo = function() {console.log('haha')};
(2)箭头函数没有自己的this指针,继承自父子作用域的上下文, 普通函数谁调用它this指向谁
var a=20;
let obj={
a:10,
fn:function(){ //谁调用它,this指向谁
console.log(this.a);
},
foo:()=>{ // this指向父级(obj)上下文。
console.log(this.a)
}
}
obj.fn(); //this指向obj, obj.a为10
obj.foo(); //this指向Window,Window.a为20
(3)箭头函数无法通过call、apply、bind改变this的指向,普通函数可以
// 箭头函数无法通过call、apply、bind改变this的指向
var a = 'Global';
let fn = () => {
console.log(this.a)
};
fn(); // 'Global'
fn.call({a: 'Obj'}); // 'Global'
fn.apply({a: 'Obj'}); // 'Global'
fn.bind({a: 'Obj'})(); // 'Global'
// 普通函数可以通过call、apply、bind改变this的指向
var a = 'Global';
let foo = function() {
console.log(this.a)
};
foo(); // 'Global'
foo.call({a: 1}); // 1
foo.apply({a: 2}); // 2
foo.bind({a: 3})(); // 3
(4)箭头函数没有arguments,有rest参数,普通函数有arguments
// 箭头函数没有arguments,有rest参数
let fn = (a,b,c) => {
console.log(arguments);
};
fn(1,2,3); //Uncaught ReferenceError: arguments is not defined
let fn = (...rest) => {
console.log(rest);
}
fn(1,2,3) //[1, 2, 3]
// 普通函数有arguments
let foo = function(a,b,c) {
console.log(arguments);
};
foo(1,2,3) //Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
(5)箭头函数没有原型属性,普通函数则有原型属性
let fn = () => {console.log('haha')};
let foo = function() {console.log('haha')};
fn.prototype //undefined
foo.prototype //{constructor: ƒ}
(6)箭头函数不能用来做构造函数,普通函数可以
通过new 方法创建一个对象的过程如下:
let a = new func() {}
- 创建一个空的简单JavaScript对象(即
{}
); - 为步骤1新创建的对象添加属性
__proto__
,将该属性链接至构造函数的原型对象 ; - 将步骤1新创建的对象作为
this
的上下文 ; - 如果该函数没有返回对象,则返回
this
;
箭头函数没有prototype,也没有this指针, 无法改变this的指向,因此箭头函数无法用来做构造函数