简体   繁体   中英

Why doesn't closure work in these functions?

Why is it that closure doesn't work here? Isn't the createTreeText() function supposed to take the text variable from function where it's called? I know that I could pass it in parameters but why can't I do this through the closure?

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

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

createTree();

Isn't the createTreeText() function supposed to take the text variable from function where it's called

No, not at all. Functions close over the variables in scope where they're created , not where they're called. All functions get from where they're called is the information passed to them as arguments (and sometimes this , depending on how they're called and what kind of function they are).

This example may clarify, see comments:

 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 is not a closure. It doesn't have access to the scope of createTree. To make it work in your example using a closure, you could try this:

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

   createTree();

Text is defined inside the scope of your first function; your second function has no reference to it at all. You can solve this a few ways, but the easiest is to just pass it as a parameter:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM