简体   繁体   English

为什么闭包在这些函数中不起作用?

[英]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? createTreeText()函数不是应该从调用它的函数中获取文本变量吗? 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 createTreeText()函数不是应该从调用它的函数中获取文本变量吗?

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取决于它们的调用方式以及它们是什么类型的函数)。

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. createTreeText不是闭包。 It doesn't have access to the scope of createTree. 它无权访问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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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