JavaScript 箭头函数与 function 函数的区别

见过箭头函数后,知道箭头函数是 function 定义函数的简写,然后还有一点是箭头函数中的 this 是上级代码的 this
其实除了这两点外,箭头函数和 function 函数还有很多区别。

1、基本语法

1
2
3
4
5
6
7
8
9
10
11
12
// 没有参数时
() => {
// code ...
}
// 有参数时
(param1, param2, ..., paramN) => {
// code ...
}
// 只有1个参数时,圆括号可以省略
param => {
// code ...
}

2、this 指向

  • 顶级代码中, this 指向 window 对象;
  • function 定义的函数中, this 指向该函数的对象;
  • 箭头函数中,箭头函数不会创建自己的 this,始终指向箭头函数所在作用域下的 this

用原型方法 apply()call()bind() 不能改变箭头函数中 this 的指向。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const bar = {
name: 'johnny'
};
function foo () {
console.log(this.name);
}

const fa = () => {
console.log(this.name);
};

// bar 作为 foo() 实例的 this
foo.call(bar); // johnny
fa.call(bar); // TypeError: Cannot read properties of undefined (reading 'name')

3、箭头函数不能做构造函数

不可以使用 new 命令创建箭头函数实例对象,因为箭头函数没有自己的 this,不能调用 call()apply
箭头函数没有 prototype 属性,而 new 命令在执行时需要将构造函数的 prototype 赋值给新的对象的 __proto__属性。

1
2
3
4
5
6
7
8
9
function fn() {
console.log(11)
}
const f = new fn();

const fa = () {
console.log(22)
}
new fa(); // TypeError: fa is not a constructor

4、箭头函数没有 arguments 对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function fn() {
console.log(arguments);
}
fn(1, 2, 3) // [Arguments] { '0': 1, '1': 2, '2': 3 }

const fa = () => {
console.log(arguments); // undefined
}

// 使用展开运算符 … 来实现类似 arguments 的调用,缺点是只有一个参数名。
let fa2 = (...args) =>{
console.log(args)
}
fa2(1, 2, 3) // [ 1, 2, 3 ]

5 对象属性的箭头函数

对象属性的箭头函数中的 this 并不是指向该对象,而是指向该对象的上一层。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function fn () {
this.a = 123;
const obj = {
a: 10,

b: function () {
console.log(this); // { a: 10, b: [Function: b], c: [Function: c], d: [Function: d] }
console.log(this.a); // 10
},

c: () => {
console.log('c this', this); // 指向 fn 函数的实例
console.log('c this.a', this.a); // 123
},

// 定义对象 function 的简写形式
d () {

}
};
obj.b();
obj.c();
}

new fn();

不可以使用 yield 命令

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

总结

箭头函数不是 没有 this 的 function 函数,并不能替代 function 函数,箭头函数更适用于需要匿名函数的地方。
建议用不到 function 函数特性的函数都用箭头函数定义,便于对函数的实现的理解。

JavaScript 箭头函数与 function 函数的区别

https://coderpan.com/front-end/javascript-arrow-function.html

作者

CoderPan

发布于

2023-02-11

更新于

2024-05-08

许可协议

评论