ES6 function函数和箭头函数区别
1.写法不一样
//function function fn(a,b){ return a+b } //arrow function var foo = (a,b)=>{ return a+b }
2.this的指向,function中的this可变(window,内部),箭头函数固定不变指向window
function foo(){ console.log(this) } var obj = {aa:foo} foo() //window obj.aa()//obj var foo = ()=>{ console.log(this) } var obj = {aa:foo} foo()//window obj.aa()//window
3.构造函数
function Person(name,age){ this.name =name this.age = age } var lenhart = new Person(lenhart,25) console.log(lenhart) //成功 var Person = (name,age)=>{ this.name = name this.age=age } var lenhart = new Person('lenhart',25) //Uncaught TypeError: Person is not a constructor
4.变量提升
foo() function foo(){ console.log('123456') } arrowFn()//Uncaught TypeError: arrowFn is not a constructor var arrowFn=()=>{ console.log('123456') }