As we discussed before (see let Prevents
Confusion), when you create local variables with let under lexical binding, those variables are valid
only within the body of the let expression. In
other parts of your code, they have other meanings, so if you call a
function defined elsewhere within the let body,
that function would be unable to “see” the local variables
you’ve created. (On the other hand, if you call a function that was
defined within a let body, that function would be able to see—and modify—the local
variables from that let expression.)
動的バインディングではルールが異なります。代わりに let を使用すると、作成したローカル変数は
let 式の実行中に有効になります。つまり、let
式が関数を呼び出す場合、その関数は定義場所(完全に別のファイルであっても)に関わらず、これらのローカル変数を参照できるということです。
動的バインディングを使用する際の let
の捉え方として、すべての変数名にはグローバルな「スタック」状のバインディングが存在し、その変数名を使用するたびにスタックの最上部にあるバインディングが参照される、という考え方があります。(これは、机の上に値を書き込んだ紙が積み重なっている様子を想像すると分かりやすいでしょう。)let で変数を動的にバインドすると、指定した新しいバインディングがスタックの最上部に追加され、その後
let の本体が実行されます。let
の本体が終了すると、そのバインディングがスタックから取り除かれ、let
式の前に存在していたバインディング(もしあれば)が明らかになります。