簡體   English   中英

如何存儲 function 的參數以在內部函數中使用

[英]How to store the argument of a function to use in inner functions

我在 NodeJS (Typescript) 中有以下類型的代碼:

private grandMotherFunction(arg1: MyObject, arg2: any){
...
aClass.motherFunction(arg1)
...

}

aClass.motherFunction 看起來像這樣:

private motherFunction(arg1: MyObject){
...
otherClass.childFunction(arg1,otherArgument)
...

}

和 otherClass.childFunction 看起來像這樣:

private childFunction(arg1: MyObject, arg2: any){
...
someOtherClass.grandChildFunction(arg1, somethingMore)
...

}

並且代碼如下所示,將相同的參數傳遞給不同類中的所有函數。 關鍵是arg1:MyObject,它只需要在granchildFunction中。 我想知道是否可以將參數存儲在某處,例如在執行線程中,然后在 grandchildFunction 中檢索它。 由於它是一個 Express 應用程序(實際上它是一個 Loopback 4.0),我曾考慮在原始請求中執行此操作,但我不希望最后一個 otherClass 導入請求。

因此,如果我理解正確,您有一個變量arg1: MyObject僅由一個 function 使用,並且 function 僅通過另一個調用,您不想通過其他函數傳遞arg1

如果是這樣,我可能會將該參數設置為this.arg1: MyObject並調用this.arg1 someOtherClass.grandChildFunction ...

所以你可以有

private grandChildFunction(arg2: any){

    otherClass.grandChildFunction(this.arg1);

}

暫無
暫無

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

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