簡體   English   中英

為什么閉包在這些函數中不起作用?

[英]Why doesn't closure work in these functions?

為什么關閉在這里不起作用? createTreeText()函數不是應該從調用它的函數中獲取文本變量嗎? 我知道我可以在參數中傳遞它,但是為什么不能在閉包中傳遞它呢?

function createTree(){
    var text = "example";
    text = createTreeText();
    console.log(text);
}

function createTreeText(){
    var newText = text.toUpperCase(); // error happens here
    return newText;
}

createTree();

createTreeText()函數不是應該從調用它的函數中獲取文本變量嗎?

一點都不。 函數在創建變量的范圍內而不是在調用位置的范圍內封閉變量。 所有函數從調用它們的位置獲得的是作為參數傳遞給它們的信息(有時this取決於它們的調用方式以及它們是什么類型的函數)。

此示例可能會澄清,請參見注釋:

 function wrapper() { var a = Math.random(); function foo() { // `foo` closes over `a`, because `a` is in scope // where `foo` was created console.log("a = " + a); // `foo` does not close over `b`, because `b` is not in scope // where `foo` was created try { console.log("b = " + b); // throws ReferenceError } catch (e) { console.log("error: " + String(e)); } } function bar() { var b = Math.random(); // Calling `foo` here does nothing to grant it access to `b` foo(); } bar(); } wrapper(); 

createTreeText不是閉包。 它無權訪問createTree的范圍。 為了使它在使用閉包的示例中起作用,可以嘗試以下操作:

function createTree(){
     var createTreeText = function(){
         var newText = text.toUpperCase(); // error happens here
         return newText;
     }
     var text = "example";
     text = createTreeText();
     console.log(text);
   }

   createTree();

文本在第一個函數的范圍內定義; 您的第二個功能根本沒有引用它。 您可以通過幾種方法解決此問題,但最簡單的方法是將其作為參數傳遞:

function createTree(){
     var text = "example";
     text = createTreeText(text);
     console.log(text);
   }

   function createTreeText(text){
     var newText = text.toUpperCase(); // error happens here
     return newText;
   }
   createTree();

暫無
暫無

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

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