为什么封闭不能在这些功能中起作用?

时间:2017-01-22 12:55:40

标签: javascript

为什么关闭在这里不起作用?是不是createTreeText()函数应该从调用它的函数中获取文本变量?我知道我可以在参数中传递它,但为什么我不能通过闭包来做到这一点?

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

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

createTree();

3 个答案:

答案 0 :(得分:4)

  

不是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();

答案 1 :(得分:1)

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();

答案 2 :(得分:0)

文本在第一个函数的范围内定义;你的第二个功能完全没有引用它。您可以通过几种方式解决这个问题,但最简单的方法是将其作为参数传递:

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

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