JavaScriptのfunctionでは、returnでcallerに返っても、内部にclosureが存在する場合、functionのargumentsやlocal変数はメモリーに駐在する。つまり外部から呼ばれるclosureがある限り、そのfunctionはメモリー内に存在する価値があるということだ。
この特殊な性質により、JavaScriptのfunctionは、他の言語のobjectのコンセプトに似てくる。objectは生成されたら、そのattributesをメモリー内に維持する。同じように、JavaScriptのfunctionは、argumentsやlocal変数をメモリーに維持する。違う点は、objectを生成するかどうかは、var object = new Object() のようにプログラマーがexplicitで決定するのに対して、JavaScriptのfunctionがメモリー内に残るかどうかは、closureがあるかどうか、つまる外部から呼ばれる関数があるかどうかで、自動的に決まる。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
function makeFunc() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
At first glance, it might seem unintuitive that this code still works. In some programming languages, the local variables within a function exist for just the duration of that function's execution. Once makeFunc() finishes executing, you might expect that the name variable would no longer be accessible. However, because the code still works as expected, this is obviously not the case in JavaScript.