簡體   English   中英

如果在內部導出,則在定義函數之前調用它是可以的

[英]Invoking a function before it is defined is ok if inside exports

以下操作因ReferenceError: f1 is not defined失敗ReferenceError: f1 is not defined

f1();
f1 = () => { console.log("f1"); }

但是以下工作原理:

exports.x = () => {
  f1();
}

f1 = () => { console.log("f1"); }

對第二種情況有何解釋?

在第一種情況下,在定義函數之前先調用該函數,這就是發生錯誤的原因:

f1(); // <- function is called before the function expression is evaluated
f1 = () => { console.log("f1"); }

在第二種情況下,根本不調用該函數,相反,將來可能由模塊使用者調用該函數。

exports.x = () => {
  f1(); // <- it will be called only if a module consumer will execute the module as a function
}

f1 = () => { console.log("f1"); }

為了將模塊作為功能調用,模塊使用者將必須導入模塊。 導入模塊時,將評估所有模塊代碼(包括我們的函數表達式)。 因此,當模塊使用者將模塊作為函數調用時,將評估函數表達式。

您可以在函數內使用任何未聲明的變量,而不會引發錯誤。

在上面的第二個示例中,未調用exports.x因此沒有錯誤。 如果您致電,它將引發錯誤。

下面是一個例子

 function test(){ console.log(x); //x is not defined still no error. } 

現在看看調用函數時會發生什么。

 function test(){ console.log(x); } test(); 

暫無
暫無

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

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