Skip to content
On this page

箭头函数的缺点

题目

什么时候不能使用箭头函数?

箭头函数的缺点

没有 arguments

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

无法通过 call apply bind 等改变 this

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

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

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

不适用箭头函数的场景

对象方法

js
const obj = {
    name: '锋哥',
    getName: () => {
        return this.name
    }
}
console.log( obj.getName() )

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

js
const obj = {
    name: '锋哥'
}
obj.__proto__.getName = () => {
    return this.name
}
console.log( obj.getName() )

构造函数

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

动态上下文中的回调函数

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

Vue 生命周期和方法

js
{
    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 中使用箭头函数则没问题

js
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 中可以使用箭头函数

js
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)

Released under the MIT License.