gpt4 book ai didi

javascript - 在类中声明之前调用常规函数与箭头函数

转载 作者:行者123 更新时间:2023-11-30 07:49:55 26 4
gpt4 key购买 nike

如果我像这样写一个 React 类:

class SomeClass extends React.Component {
state = {
someState: this.someRegularFunction(),
someOtherState: this.someArrowFunction()
};

someRegularFunction() {
return "someText";
}

someArrowFunction = () => {
return "someOtherText";
};
}

Webstorm 代码帮助警告关于调用箭头函数 this.someArrowFunction() 说:

Field 'someArrowFunction' is declared after 'state' and is possibly not assigned yet

如果不警告调用常规函数 this.someRegularFunction()

而且 Webstorm 是正确的,调用 this.someArrowFunction() 时执行失败:

TypeError: _this.someArrowFunction is not a function


我一直在寻找一些解释此行为的文档,但找不到任何文档。

为什么在类中声明之前可以调用常规函数,但不能调用箭头函数?

最佳答案

因为该代码在功能上与此相同:

class SomeClass extends React.Component {
constructor(...args) {
super(...args);
this.state = {
someState: this.someRegularFunction(),
someOtherState: this.someArrowFunction()
};
this.someArrowFunction = () => {
return "someOtherText";
};
}

someRegularFunction() {
return "someText";
}
}

创建实例 时,字段定义按源代码顺序处理。就好像它们是在任何其他代码之前(在基类中)或在调用 super 之后(在子类中)插入到构造函数中一样。

相比之下,someRegularFunction 是原型(prototype)的一个方法,它是在评估类定义时创建的,而不是稍后创建实例时创建的。

the proposal for the class fields feature 涵盖了这一点, 在规范文本中。 (不过,阅读规范文本不适合胆小的人!:-))


旁注:这可以说是样式问题,但是如果您正在执行箭头函数以便它可以使用 this 而不必担心它是如何调用的(例如,作为事件处理程序),您可能会考虑将其设为一个方法,然后在构造函数中(或有效地在构造函数中)使用 bind 代替:

class SomeClass extends React.Component {
someFunction = this.someFunction.bind(this);
state = {
someState: this.someRegularFunction(),
someOtherState: this.someFunction()
};

someRegularFunction() {
return "someText";
}

someFunction() {
return "someOtherText";
}
}

这更适合可能需要模拟函数的测试代码(通过在原型(prototype)上替换它)。

但同样,这可以说是一个风格问题。

关于javascript - 在类中声明之前调用常规函数与箭头函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54944937/

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