1. 写法不同
let func1 = () =>{ //匿名函数
console.log('func1')
}
function func2(){ //具名函数
console.log('func2')
}
let func3 = function(){ //匿名函数
console.log('func3')
}
普通函数可以有匿名函数,也可以有具体名函数,但是箭头函数都是匿名函数。
箭头函数中不可加new,也就是说箭头函数不能当构造函数进行使用。
2. this指向的不同
- 普通函数
在普通函数中,this总是指向调用它的对象,如果没有调用者则默认指向window,如果用作构造函数,this指向创建的对象实例。 - 箭头函数
箭头函数中的this指向是固定不变的,一直指向的是定义函数的环境。
1). 默认指向定义它时,所处上下文的对象的this指向。即ES6箭头函数里this的指向就是上下文里对象this指向,偶尔没有上下文对象,this就指向window
2). 即使是call,apply,bind等方法也不能改变箭头函数this的指向
// hello是全局函数,没有直接调用它的对象,也没有使用严格模式,this指向window
function hello() {
console.log(this); // window
}
hello();
// hello是全局函数,没有直接调用它的对象,但指定了严格模式('use strict'),this指向undefined
function hello() {
'use strict';
console.log(this); // undefined
}
hello();
// hello直接调用者是obj,第一个this指向obj,setTimeout里匿名函数没有直接调用者,this指向window
const obj = {
num: 10,
hello: function () {
console.log(this); // obj
setTimeout(function () {
console.log(this); // window
});
}
}
obj.hello();
// hello直接调用者是obj,第一个this指向obj,setTimeout箭头函数,this指向最近的函数的this指向,即也是obj
const obj = {
num: 10,
hello: function () {
console.log(this); // obj
setTimeout(() => {
console.log(this); // obj
});
}
}
obj.hello();
3. 变量提升
由于js的内存机制,function的级别最高,而用箭头函数定义函数的时候,需要var(let const定义的时候更不必说)关键词,而var所定义的变量不能得到变量提升,故箭头函数一定要定义于调用之前!
foo(); //123
function foo(){
console.log('123');
}
arrowFn(); //Uncaught TypeError: arrowFn is not a function
var arrowFn = () => {
console.log('456');
};
参考了下其他博主的一些见解,更多不同,待后续更新。