当前位置:网站首页>箭头函数和普通函数的常见区别
箭头函数和普通函数的常见区别
2022-08-09 11:54:00 【曲鸟】
一、前言
使用JS经常会看到如下写法来定义函数:
第一种:const App= () => {
} //箭头函数
第二种:function App() {
} //普通函数
他们之间除了长的不一样还有一些区别是我们需要注意的,这里给大家介绍一下。
二、箭头函数和普通函数的常见区别
1)写法不同
箭头函数比普通函数更简洁:
//普通函数
const sum = function sum(a, b) {
return a + b
}
//箭头函数 相当于python的匿名函数了
const sum = (a, b) => a + b
箭头函数的写法跟Python中的匿名函数类似。
2)箭头函数没有自己的this
箭头函数不能作为构造函数,也没有自己的this,它只会在自己作用域的上一层继承this。所以箭头函数中this的指向在它在定义时已经确定了,之后不会改变:
var id = '1';
var obj = {
id: '2',
a: function(){
console.log(this.id);
},
b: () => {
console.log(this.id);
}
};
obj.a(); // '2'
obj.b(); // '1'
new obj.a() // undefined
new obj.b() // Uncaught TypeError: obj.b is not a constructor
3)普通函数有arguments方法,箭头函数没有
f1(12,23,45);
//普通函数
const f1 = function () {
console.log(arguments);//Arguments(3) [12, 23, 45, callee: (...), Symbol(Symbol.iterator): ƒ]
}
//箭头函数
const f1 = () => console.log(arguments);// Throws an error - arguments is not defined
//箭头函数可以使用rest语法解决
const f1 = (...args) => console.log(args);//[12, 23, 45]
4)箭头函数没有new.target
new.target是用来检测函数是否被当做构造函数使用,他会返回一个指向构造函数的引用:
箭头函数打印new.target出现报错

5)箭头函数没有变量提升
变量提升即将变量声明提升到它所在作用域的最开始的部分,如下面的代码所示:
func();
function func(){
console.log("aa");
}
func的调用执行可以定义在函数创建之前,也不会报错,但箭头函数则不行:
6)箭头函数不能作为构造函数使用
普通函数
function Cls(a,b) {
this.a=a
this.b=b
}
let obj=new Cls(1,2)
console.log(obj.a) //1
箭头函数
let Cls = (a, b) => {
this.a = a
this.b = b
}
let obj = new Cls(1, 2)
console.log(obj.a)//undefiend
三、总结
经过上述分析发现普通函数的功能会比箭头函数更强大一些,但这也不是说我们就要避免使用箭头函数。而是应该根据实际的应用场景来选择。对于使用react hooks来开发前端的我而言,基本很少使用普通函数,大部分的箭头函数使用也未造成开发的影响,代码反而简洁了不少。这两者也没有谁优谁劣的说法,看个人喜好来选择也是可以的。没必要在这些问题上花费过多的时间去争论,哪种让自己用起来更舒服用哪种就行。
边栏推荐
猜你喜欢

IDEA 关闭/开启引用提示Usages
![[现代控制理论]3_Phase_portrait 相图 相轨迹](/img/45/255a6a62f8be320c663f5fcad1ad1b.png)
[现代控制理论]3_Phase_portrait 相图 相轨迹

阻塞、非阻塞、多路复用、同步、异步、BIO、NIO、AIO 一锅端

ARP协议原理

Double pointer - the role of char **, int **

web course design
![[Essence] Analysis of the special case of C language structure: structure pointer / basic data type pointer, pointing to other structures](/img/cc/9e5067c9cedaf1a1797c0509e67f88.png)
[Essence] Analysis of the special case of C language structure: structure pointer / basic data type pointer, pointing to other structures

ThreadLocal的简单理解

shell脚本------函数的格式,传参,变量,递归,数组

Visual Studio 2017 ASP.NET Framework MVC 项目 MySQL 配置连接
随机推荐
阿里云新增三大高性能计算解决方案,助力生命科学行业快速发展
Blazor Server (9) from scratch -- modify Layout
ACM longest non-descent subsequence problem
Shell之常用小工具(sort、uniq、tr、cut)
Oracle Database Architecture
Gumbel_Softmax 概要
BeanFacroty和FactoryBean到底是什么?AppliacationContext它又是什么?
防止数据冒用的方法
WPF implements a MessageBox message prompt box with a mask
【Basic model】Transformer-实现中英翻译
PAT1003
Django cannot link mysql database
拍频造成的轻微震荡
[现代控制理论]2_state-space状态空间方程
抗积分饱和 PID代码实现,matlab仿真实现
父类的main方法可以被继承么?有什么特殊?
【小程序】低代码+小游戏=小游戏可视化开发
wpf path xaml写法和c#写法对比
IDEA close/open reference prompt Usages
PAT1012