本篇文章给大家带来的内容是关于es6箭头函数与function有什么区别?有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
1.写法不同
// function的写法function fn(a, b){ return a+b;}
// 箭头函数的写法let foo = (a, b) =>{ return a + b }
2.this的指向不同
在function中,this指向的是调用该函数的对象;
//使用function定义的函数function foo(){ console.log(this);}var obj = { aa: foo };foo(); //windowobj.aa() //obj { aa: foo }
而在箭头函数中,this永远指向定义函数的环境。
//使用箭头函数定义函数var foo = () => { console.log(this) };var obj = { aa:foo };foo(); //windowobj.aa(); //window
function timer() { this.s1 = 0; this.s2 = 0; // 箭头函数 setinterval(() => { this.s1++; console.log(this); }, 1000); // 这里的this指向timer // 普通函数 setinterval(function () { console.log(this); this.s2++; // 这里的this指向window的this }, 1000);}var timer = new timer();settimeout(() => console.log('s1: ', timer.s1), 3100);settimeout(() => console.log('s2: ', timer.s2), 3100);// s1: 3// s2: 0
3.箭头函数不可以当构造函数//使用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
另外,由于箭头函数没有自己的this,所以当然也就不能用call()、apply()、bind()这些方法去改变this的指向。
4.变量提升function存在变量提升,可以定义在调用语句后;
foo(); //123function foo(){ console.log('123');}
箭头函数以字面量形式赋值,是不存在变量提升的;
arrowfn(); //uncaught typeerror: arrowfn is not a functionvar arrowfn = () => { console.log('456');};
console.log(f1); //function f1() {} console.log(f2); //undefined function f1() {}var f2 = function() {}
以上就是es6箭头函数与function有什么区别?的详细内容。