Javascript 类方法与属性 [英] Javascript class methods versus properties

查看:36
本文介绍了Javascript 类方法与属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've seen code using Javascript classes use the following form (example is React):

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

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

为什么将 handleOpen 实现为设置为函数的属性而不是类似的属性:

Why is handleOpen implemented as a property which is set to a function instead of something like:

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

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

提前致谢!

推荐答案

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

That's also a function, but it's called an arrow function and works slightly differently from the "traditional" implementation. It was introduced with ECMAScript 6.

以下是 MDN 文档 说:

Here's what the MDN docs says:

箭头函数表达式的语法比 函数表达式并且不绑定自己的this, 参数supernew.target.这些函数表达式最适合非方法函数,它们不能用作构造函数.

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 绑定到该函数,因为箭头函数没有自己的 this 对象:


One of the major benefits is that you wouldn't need to bind this to that function, because arrow functions do not have their own this object:

在箭头函数之前,每个新函数都定义了自己的 this 值

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

这保证了范围安全;不可能偶然使用不正确的this.可以说,它的可读性也略高一些.

This guarantees scope safety; it's impossible to use the incorrect this by accident. It is arguably also slightly more readable.

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

A drawback however would be that arrow functions are anonymous, meaning that it would be harder to do a stack trace when you get an error in your code.But for React applications we can use devtool:'cheap-module-eval-source-map' from babel to easily find bugs in our stack trace.

这篇关于Javascript 类方法与属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆