箭头函数的缺点,什么时候不能使用箭头函数?

箭头函数的缺点

没有 arguments

const fn1 = () => {
    console.log('this', arguments) // 报错,arguments is not defined
}
fn1(100, 200)

无法通过 call apply bind 等改变 this

const fn1 = () => {
    console.log('this', this) // window
}
fn1.call({ x: 100 })

简写的函数会变得难以阅读

const multiply = (a, b) => b === undefined ? b => a * b : a * b

不适用箭头函数的场景

对象方法

const obj = {
    name: '双越',
    getName: () => {
        return this.name
    }
}
console.log( obj.getName() )

扩展对象原型(包括构造函数的原型)

const obj = {
    name: '双越'
}
obj.__proto__.getName = () => {
    return this.name
}
console.log( obj.getName() )

构造函数

const Foo = (name, age) => {
    this.name = name
    this.age = age
}
const f = new Foo('张三', 20) // 报错 Foo is not a constructor

动态上下文中的回调函数

const btn1 = document.getElementById('btn1')
btn1.addEventListener('click', () => {  
    // console.log(this === window)
    this.innerHTML = 'clicked'
})

Vue 生命周期和方法

{
    data() { return { name: '双越' } },
    methods: {
        getName: () => {
            // 报错 Cannot read properties of undefined (reading 'name')
            return this.name
        },
        // getName() {
        //     return this.name // 正常
        // }
    },
    mounted: () => {
        // 报错 Cannot read properties of undefined (reading 'name')
        console.log('msg', this.name)
    },
    // mounted() {
    //     console.log('msg', this.name) // 正常
    // }
}

【注意】class 中使用箭头函数则没问题

class Foo {
    constructor(name, age) {
        this.name = name
        this.age = age
    }
    getName = () => {
        return this.name
    }
}
const f = new Foo('张三', 20)
console.log('getName', f.getName())

所以,在 React 中可以使用箭头函数

export default class HelloWorld extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            name: '双越'
        }
    }
    render() {
        return <p onClick={this.printName}>hello world</p>
    }
    printName = () => {
        console.log(this.state.name)
    }
}

答案

箭头函数的缺点

  • arguments 参数
  • 无法改变 this

不适用的场景

  • 对象方法
  • 对象原型
  • 构造函数
  • 动态上下文
  • Vue 生命周期和方法

划重点

  • Vue 组件是一个对象,而 React 组件是一个 class (如果不考虑 Composition API 和 Hooks)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值