簡體   English   中英

在類中聲明常規函數和箭頭函數之前先調用它們

[英]Calling regular function vs. arrow function before their declaration in a class

如果我這樣寫一個React類:

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

    someRegularFunction() {
        return "someText";
    }

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

Webstorm代碼幫助警告有關箭頭函數this.someArrowFunction()的調用,該說法是:

字段“ someArrowFunction”在“狀態”之后聲明,可能尚未分配

如果不警告常規函數的調用this.someRegularFunction()

而且Webstorm是正確的,調用this.someArrowFunction()時執行失敗:

TypeError:_this.someArrowFunction不是函數


我一直在尋找解釋此行為的文檔,但一直找不到。

為什么在類中聲明常規函數之前不能調用箭頭函數?

因為該代碼在功能上與此相同:

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是原型的方法,該方法在評估類定義時創建,而不是在實例創建后創建。

規范文本中有關類字段功能的建議對此進行了介紹。 (不過,閱讀規范文本並不適合膽小者!:-))


旁注:可以說是樣式問題,但是如果您執行箭頭功能,以便它可以使用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";
    }
}

這對於可能需要模擬該功能的測試代碼(通過在原型上進行替換)更有效。

但同樣,這可以說是風格問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM