【JavaScript】普通函数和箭头函数的区别

Posted by ARTROY on 2019-10-30

普通函数与箭头函数

1
2
3
4
5
6
7
8
9
10
11
12
'use strict';

// 普通函数
var fun1 = () => {
console.log(this);
}
// 箭头函数
var fun2 = function() {
console.log(this);
}
fun1(); // undefined
fun2(); // window

普通函数和箭头函数的区别

1、语法

箭头函数的定义要比普通函数定义简洁、清晰得多,很快捷。

1
2
3
4
5
6
// 普通函数
var arr1 = [1, 3, 5, 2, 6].sort(function (a, b) {
return a - b;
});
// 箭头函数
var arr2 = [1, 3, 5, 2, 6].sort((a, b) => a - b);

2、使用new操作符

箭头函数不能用作构造器,和 new 一起用就会抛出错误。

1
2
3
4
5
6
// 普通函数
var Foo1 = function() {};
var foo1 = new Foo1();
// 箭头函数
var Foo2 = () => {};
var foo2 = new Foo2(); // Foo2 is not a constructor

3、箭头函数不能用作Generator函数

箭头函数不能用·Generator函数,不可以使用yield命令。

4、函数中this的指向(重点)

(1) 箭头函数继承而来的this指向永远不变

1
2
3
4
5
6
7
8
9
10
11
12
13
var id = 'GLOBAL';
var obj = {
id: 'OBJ',
a: function(){
console.log(this.id);
},
b: () => {
console.log(this.id);
}
};

obj.a(); // 'OBJ'
obj.b(); // 'GLOBAL'

(2) call()/.apply()/.bind()无法改变箭头函数中this的指向,能改变普通函数的指向。

1
2
3
4
5
6
7
8
9
var id = 'Global';
// 箭头函数定义在全局作用域
let fun1 = () => {
console.log(this.id)
};
fun1(); // 'Global'
fun1.call({id: 'Obj'}); // 'Global'
fun1.apply({id: 'Obj'}); // 'Global'
fun1.bind({id: 'Obj'})(); // 'Global'


支付宝打赏 微信打赏

欣赏此文,打赏一下



-->