Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I only declare variables in the first instance of a chain of nested closures?

I'm trying to hack together a Read-Eval-Print-Loop in Javascript. (It's for a web-based "teach yourself Javascript" platform.) I have something that mostly works, but I'm encountering a weird bug with closures.

Here's a simplified version of the core of the loop. I wrote it this way because I want to use closures and continuations to maintain any state created in the eval:

// listing 1

var repl = function(result) {
  return {
    result:
      result,
    then:
      function (expression, continuation) {
        return continuation(eval(expression));
      },
  };
}

And it almost works. For instance, it correctly evaluates the sequence of expressions var x = 1, x++, x:

// listing 2

repl(eval('var x = 1')).then('x++', repl)
                       .then('x', repl)
                       .result

// evaluates to 2

So expressions can access and modify local variables that were declared earlier without polluting the global scope, which is great. But the variable declaration (i.e. var ...) only works in for the first expression in the chain. For instance, the sequence of expressions var x = 1, var y = 2, y throws a y is not defined error:

// listing 3

repl(eval('var x = 1')).then('var y = 2', repl)
                       .then('y', repl)
                       .result;

// throws "y is not defined"

I've found that I can avoid this error if I replace each instance of repl with its definition, like this:

//listing 4
//
// same as listing 3, but repl is replaced with its
// definition from listing 1

function (result) {
    return {
      result:
        result,
      then:
        function (expression, continuation) {
          return continuation(eval(expression));
        }
    },
  })(eval('var x = 1')).then(
    'var y = 2',
    function (result) {
      return {
        result:
          result,
        then:
          function (expression, continuation) {
            return continuation(eval(expression));
          },
      };
    }
  ).then(
    'y',
    function (result) {
      return {
        result:
          result,
        then:
          function (expression, continuation) {
            return continuation(eval(expression));
          },
      };
    }
  ).result

// evaluates to 2

This evaluates to 2. So I guess I could solve my problem just by evaling the definition of repl for each iteration. But surely there's a better solution ... isn't there?


Edit: I experimented with replacing each instance of repl with eval('('+repl+')'), but it didn't solve the problem. What am I missing?

like image 731
Pitarou Avatar asked Jan 31 '26 17:01

Pitarou


1 Answers

Since RobG already explained the cause of the problem, I'll limit this answer to a possible workaround.

If you do not mind polluting the global scope (maybe that's even desired here?), you can use an indirect eval call to force all the expressions to be evaluated globally:

var repl = function(result) {
  return {
    result:
      result,
    then:
      function (expression, continuation) {
        return continuation((1,eval)(expression));
      },
  };
}

http://jsfiddle.net/y37Pj/

You could also call repl instead of continuation, so you don't need to pass it to then every time:

var repl = function(result) {
  return {
    result:
      result,
    then:
      function (expression) {
        return repl((1,eval)(expression));
      },
  };
}

repl(eval('var x = 1')).then('var y = 2')
                       .then('y')
                       .result

http://jsfiddle.net/y37Pj/1/


The solution Pitarou accepted was hidden in a jsFiddle in a comment to this answer. For reference, here's a slightly modified version of the "ugly hack" solution (which evals the source code of the function to create a closure):

function make_repl() {
  return {
    result: undefined,
    then: function (expression) {
      return {
        result: eval(expression),
        then: eval('('+this.then.toString()+')'),
      };
    },
  };
};

var repl = make_repl();

repl = repl.then('var x = 1').then('var y = 2').then('x + " " + y');

console.log(repl.result); // prints "1 2"

console.log(typeof(x), typeof(y));
// prints "undefined undefined", so we know the global scope was not touched
like image 86
bfavaretto Avatar answered Feb 02 '26 05:02

bfavaretto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!