gpt4 book ai didi

Javascript 类方法与属性

转载 作者:数据小太阳 更新时间:2023-10-29 05:21:27 24 4
gpt4 key购买 nike

我见过使用 Javascript 类的代码使用以下形式(例如 React):

class UserProfile extends Component {
state = {
open: false
}

handleOpen = () => {
this.setState({ open: true })
}
}

为什么 handleOpen 实现为设置为函数的属性,而不是像这样的东西:

class UserProfile extends Component {
state = {
open: false
}

handleOpen() {
this.setState({ open: true })
}
}

提前致谢!

最佳答案

这也是一个函数,但它被称为箭头函数,其工作方式与“传统”实现略有不同。它是在 ECMAScript 6 中引入的。

这是 MDN docs 的内容说:

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.


其中一个主要好处是您不需要将 this 绑定(bind)到该函数,因为箭头函数没有它们自己的 this 对象:

Until arrow functions, every new function defined its own this value

这保证了范围安全;不可能偶然使用不正确的 this。它也可以说更具可读性。

然而,缺点是箭头函数是匿名的,这意味着当您在代码中遇到错误时,很难进行堆栈跟踪。但是对于 React 应用程序,我们可以使用 devtool:'cheap-module-eval-来自 babel 的 source-map' 可以轻松地在我们的堆栈跟踪中找到错误。

关于Javascript 类方法与属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44423947/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com