ClojureScript如何编译闭包?

Eli*_*der 3 closures clojure clojurescript

当使用ClojureScript时,我尝试定义一个函数,它是对变量的闭包,如下所示:

(let [x 42] 
  (defn foo [n] (+ x n)))
Run Code Online (Sandbox Code Playgroud)

在Rhino REPL打印以下来源:

function foo(n){
  return cljs.core._PLUS_.call(null,x__43,n);
}
Run Code Online (Sandbox Code Playgroud)

该函数按照我的预期工作,但是当试图获取名为的变量时,x__43我无法得到它.它去了哪里?

Joo*_*aat 5

x变量在foo函数之外定义,在let绑定中.你不能"得到它",因为你不在let绑定的范围内.这或多或少是使用闭包的重点.

从概念上讲,让绑定实现为函数调用:

(let [x 2] ...)
Run Code Online (Sandbox Code Playgroud)

相当于

((fn [x] ...) 2)
Run Code Online (Sandbox Code Playgroud)

可能类似于let在ClojureScript中实现 - 作为宏转换fn或直接转换为(function(x){...})(2).