Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ClojureScript compile closures?

When using ClojureScript I tried to define a function that is a closure over a variable like this:

(let [x 42] 
  (defn foo [n] (+ x n)))

That prints the following source at the Rhino REPL:

function foo(n){
  return cljs.core._PLUS_.call(null,x__43,n);
}

The function works as I expect but when trying to get at the variable named x__43 I can't get it. Where did it go?

like image 978
Eli Schneider Avatar asked Jun 14 '26 15:06

Eli Schneider


1 Answers

the x variable is defined outside the foo function, in the let binding. you can't "get it" because you're not in the scope of the let binding. that's more or less the whole point of using closures.

conceptually, let bindings are implemented as function calls:

(let [x 2] ...)

is equivalent to

((fn [x] ...) 2)

which is probably similar to let is implemented in ClojureScript - either as a macro transformation to fn or directly to (function(x){...})(2).

like image 183
Joost Diepenmaat Avatar answered Jun 16 '26 15:06

Joost Diepenmaat