0

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(); 
3
  • 1
    Add your code as "code", not using image. Commented Jan 22, 2017 at 12:57
  • 1
    Why don't you just pass text as a parameter? Commented Jan 22, 2017 at 12:57
  • in the second function, it seems that text is an unknow variable, because it is defined in the first function only. Commented Jan 22, 2017 at 13:15

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.