箭头函数 普通函数 的 区别

本文详细探讨了JavaScript中的箭头函数与普通函数的区别,包括书写格式、参数处理、this指向、原型与构造函数以及变量提升等方面。箭头函数不适用new操作符,this始终指向定义时的作用域,而普通函数的this取决于调用方式。此外,箭头函数内部无法使用yield,不能作为Generator函数。
摘要由CSDN通过智能技术生成

一、书写格式

1. 箭头函数

  • 只有一个参数,小括号可以省略;没有参数时括号不能省略
  • 函数体中只有一行代码时,大括号可以省略;返回值为对象类型时,需要用 () 括起来
const fn = () => {}

const fnReturnObject = () => ({})

2. 普通函数

function fn() {}

二、参数

1. 箭头函数

  • rest参数… (真数组)
const fn = (...args) => console.log(args) // fn(1, 2, 3) -> [ 1, 2, 3 ]

2. 普通函数

  • arguments (伪数组)
function fn() {
	console.log(arguments)
}
// fn(1, 2, 3) -> [Arguments] { '0': 1, '1': 2, '2': 3 }

三、this指向

1. 箭头函数

  • this指向上层函数作用域的this对象,如果没有上层函数作用域,则指向顶部 this (在浏览器中顶部 this 则是 window)
const fn = () => console.log(this) // fn() -> Window

2. 普通函数

  • this指向该函数的调用者
const obj = {
	fn() {
		console.log(this)
	}
}
// obj.fn() -> {fn: ƒ} (obj)

3. call, apply, bind 修改 this 指向

  • call、apply、bind 会改变普通函数的 this,但不会改变箭头函数的 this
const obj = {
	a: 1
}

function fn1 () {
	console.log(this.a)
}
// fn1.call(obj) -> 1
// fn1.apply(obj) -> 1
// fn1.bind(obj)() -> 1

const fn2 = () => console.log(this.a)
// fn2.call(obj) -> undefined
// fn2.apply(obj) -> undefined
// fn2.bind(obj)() -> undefined

四、原型和构造函数

1. 箭头函数

  • 不能使用 new 生成实例,因为箭头函数没有 prototype,而 construct 在 prototype 里面
const fn = () => {}

// const f = new fn() -> TypeError: fn is not a constructor
// console.log(fn.prototype) -> undefined

2. 普通函数

function fn() {}

// const f = new fn() -> {}
// console.log(fn.prototype) -> {constructor: ƒ}

五、变量提升

1. 箭头函数

  • 使用 let、const 定义箭头函数,不会变量提升
fn() // ReferenceError: fn is not defined

let fn = () => {}
// const fn = () => {}
  • 使用 var 定义箭头函数,变量提升,但没有初始化
fn() // TypeError: fn is not a function

var fn = () => {}

2. 普通函数

  • 普通函数在定义之前能够正常调用
fn() // 'fn called'

function fn() {
  console.log('fn called')
}

六、其他

  1. 箭头函数内不能用 yield 且不能用作 Generator 函数,而普通函数可以。
  2. … …
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值