本文摘自PHP中文网,作者不言,侵删。
本篇文章给大家带来的内容是关于ES6箭头函数与function有什么区别?有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。1.写法不同
1 2 3 4 | function fn(a, b){
return a+b;
}
|
1 2 | let foo = (a, b) =>{ return a + b }
|
2.this的指向不同
在function中,this指向的是调用该函数的对象;
1 2 3 4 5 6 7 | function foo(){
console.log(this);
}
var obj = { aa: foo };
foo();
obj.aa()
|
而在箭头函数中,this永远指向定义函数的环境。
1 2 3 4 5 | var foo = () => { console.log(this) };
var obj = { aa:foo };
foo();
obj.aa();
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | function Timer() {
this.s1 = 0;
this.s2 = 0;
setInterval(() => {
this.s1++;
console.log(this);
}, 1000);
setInterval( function () {
console.log(this);
this.s2++;
}, 1000);
}
var timer = new Timer();
setTimeout(() => console.log( 's1: ' , timer.s1), 3100);
setTimeout(() => console.log( 's2: ' , timer.s2), 3100);
|
3.箭头函数不可以当构造函数
1 2 3 4 5 6 7 | function Person(name, age){
this.name = name;
this.age = age;
}
var lenhart = new Person(lenhart, 25);
console.log(lenhart);
|
1 2 3 4 5 6 | var Person = (name, age) =>{
this.name = name;
this.age = age;
};
var lenhart = new Person( 'lenhart' , 25);
|
另外,由于箭头函数没有自己的this,所以当然也就不能用call()、apply()、bind()这些方法去改变this的指向。
4.变量提升
function存在变量提升,可以定义在调用语句后;
1 2 3 4 | foo();
function foo(){
console.log( '123' );
}
|
箭头函数以字面量形式赋值,是不存在变量提升的;
1 2 3 4 | arrowFn();
var arrowFn = () => {
console.log( '456' );
};
|
1 2 3 4 | console.log(f1);
console.log(f2);
function f1() {}
var f2 = function () {}
|
以上就是ES6箭头函数与function有什么区别?的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
typescript和javascript的区别有哪些
javascript运行没有效果是怎么回事?
javascript如何设置select值
javascript是编译语言吗
学习用 javascript 实现归并排序
javascript怎么设置img内容
javascript现继承的四种方式(代码示例)
学会html能做什么工作
什么是并发控制?javascript中如何实现并发控制?
javascript语言支不支持多线程
更多相关阅读请进入《javascript》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » ES6箭头函数与function有什么区别?