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

一、外形不同

箭头函数是用箭头定义。

// 普通函数
function func(){
}
// 箭头函数
const func=()=>{
}

二、命名

普通函数可以是匿名函数和具名函数,而箭头函数只能是匿名函数。

// 具名函数
function func(){
}
 
// 匿名函数
let func = function(){
}

// 箭头函数都是匿名函数
let func=()=>{
}

三、构造函数

就因为箭头函数都是匿名函数,所以不能作为构造函数,不能使用new。

let a = () => { console.log(111)} 
a()
/// 111

let fn = new a()
/// VM82:4 Uncaught TypeError: a is not a constructor at <anonymous>:4:10

四、this

箭头函数本身不绑定this,会捕获其所在的定义时上下文的this值,作为自己的this值,而且通过apply()bind()call() 改变不了this 的指向。

普通函数中的this指向调用它的对象,具体要根据情况而定。

五、arguments

每一个普通函数调用后都具有一个arguments对象,用来存储实际传递的参数。但是箭头函数并没有此对象。

箭头函数不绑定arguments,取而代之用rest参数…解决。

function A(a){
  console.log(arguments);
}
A(1,2,3,4,5,8);  //  [1, 2, 3, 4, 5, 8, callee: ƒ, Symbol(Symbol.iterator): ƒ]


let B = (b)=>{
  console.log(arguments);
}
B(2,92,32,32);   // Uncaught ReferenceError: arguments is not defined


let C = (...c) => {
  console.log(c);
}
C(3,82,32,11323);  // [3, 82, 32, 11323]

五、原型对象

普通函数都有原型对象,而箭头函数没有原型对象。

function c() {}
c.prototype
// {constructor: ƒ}

let cc = () => {}
cc.prototype
// undefined

六、Generator函数

箭头函数不能当做Generator函数,不能使用yield关键字,因为标准规范定义了生成器必须是function*

七、简写方式

箭头函数如果return一个对象的情况下可以使用 () 包裹简写

//简化前
const fun = () => {
  return {a:1}
}

// 简写后
const fun = () => ({a:1})
posted @ 2022-04-14 10:47  AvenCheung  阅读(295)  评论(0编辑  收藏  举报