ES6箭头函数和function的区别

1. 写法

// function
function fn(a, b){
    return a + b;
}
// arrow function
var foo = (a, b)=>{ return a + b };

2. this 的指向

使用 function 定义的函数,this 的指向随着调用环境的变化而变化的,而箭头函数中的 this 指向是固定不变的,一直指向的是定义函数的环境。

使用 function 定义的函数中 this 指向是随着调用环境的变化而变化的。

// 使用function定义的函数
function foo(){
    console.log(this);
}
var obj = { aa: foo };
foo();         //    Window
obj.aa()     //    obj { aa: foo }

明显使用箭头函数的时候,this的指向是没有发生变化的。

//使用箭头函数定义函数
var foo = () => { console.log(this) };
var obj = { aa:foo };
foo(); //Window
obj.aa(); //Window

3. 构造函数

function 是可以定义构造函数的,而箭头函数是不行的。

// 使用function方法定义构造函数
function Person(name, age){
    this.name = name;
    this.age = age;
}
var lenhart =  new Person(lenhart, 25);
console.log(lenhart); // {name: 'lenhart', age: 25}
//尝试使用箭头函数
var Person = (name, age) =>{
    this.name = name;
    this.age = age;
};
var lenhart = new Person('lenhart', 25); //Uncaught TypeError: Person is not a constructor

4.变量提升

由于 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');
};