func()=>和有什么区别? {}和func =()=> {} 在班上? [英] What is the difference between func() => {} and func = () => {} in class?
问题描述
我现在正在学习使用 Class
语法现在创建React组件,并注意我现在必须声明这样的方法:
I'm learning to use Class
syntax now to create React components now and notice I now have to declare methods like this:
class Foo extends React.Component {
...
bar = () => {
this.setState({ ... })
}
}
而不是这样:
class Foo extends React.Component {
...
bar() {
this.setState({ ... }) // won't work
}
}
否则我不能使用 this.setState()
。
有人能解释一下创建这样的方法以及它们与函数原型之间的区别吗?
Can anybody explain what's the difference between creating methods like this and how they are related to the function prototype?
推荐答案
首先是依赖 类字段 尽管它们是第3阶段的提案,并且可能很快会被采用,但仍是该语言的一部分。该代码在实例上设置了一个属性(就像在构造函数中一样),该属性是一个箭头函数(因此关闭了 this
)。等效于此:
The first is relying on class fields, which aren't yet part of the language although they're a Stage 3 proposal and likely to be adopted soon. That code is setting a property on the instance (as though it were in the constructor) which is an arrow function (and thus closes over this
). It's equivalent to this:
class Foo extends React.component {
constructor() {
this.bar = () => {
this.setState({ ... })
};
}
}
第二种是方法语法,它在 prototype
对象,该对象用作新实例的原型,对于 this
(例如,此
里面的内容取决于调用方式)。
The second is method syntax, which creates a property on the prototype
object that gets used as the prototype of new instances, and which is a "normal" function in terms of this
(e.g., what this
is inside it depends on how it's called).
它们之间的区别 的处理意义重大:这意味着,如果您使用
bar
作为道具,那么在第一个示例中,您不会不必担心这种
管理(但是您要为每个实例创建一个新函数);使用方法语法,您确实需要担心这种
管理(这最终可能会根据您的处理方式创建新函数)。
The difference between them in terms of this
handling is significant: It means that if you use bar
as a prop, with the first example you don't have to worry about this
management (but you're creating a new function for every instance); with the method syntax, you do have to worry about this
management (which also can end up creating a new function, depending on how you handle it).
这篇关于func()=>和有什么区别? {}和func =()=> {} 在班上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!