🗂
PythonのクロージャとJavaScriptのクロージャ、実装の違い
Pythonのクロージャ
- 定義方法: 関数の中で別の関数を定義し、内側の関数が外側の関数の変数を参照する。
def outer_function(text):
def inner_function():
print(text)
return inner_function
closure = outer_function('Hello, Python!')
closure() # Output: Hello, Python!
-
再代入の制限:
nonlocal
キーワードが必要。
def outer_function(count):
def inner_function():
nonlocal count
count += 1
print(count)
return inner_function
closure = outer_function(10)
closure() # Output: 11
-
globalキーワードの使い方:
global
キーワードで関数内からグローバル変数を参照および更新。これによりクラスを書かずに関数の中だけで値を管理することが可能になる。
count = 0
def outer_function():
global count
count += 1
print(count)
outer_function() # Output: 1
outer_function() # Output: 2
JavaScriptのクロージャ
- 定義方法: 関数の中で別の関数を定義し、内側の関数が外側の関数の変数を参照する。returnのなかにアロー関数やfunctionを直接書き込むことでも実装は可能。
function outerFunction(text) {
function innerFunction() {
console.log(text);
}
return innerFunction;
}
var closure = outerFunction('Hello, JavaScript!');
closure(); // Output: Hello, JavaScript!
-
再代入の制限: Pythonでは
nonlocal
キーワードが必要だが、JavaScriptでは不要。const
を使用する場合は再代入に制限がかかる。
function outerFunction(count) {
function innerFunction() {
count++;
console.log(count);
}
return innerFunction;
}
let closure = outerFunction(10);
closure(); // Output: 11
- count変数の定義: 外部関数で変数を定義し、クロージャ内で使用。
function outerFunction(initialCount) {
let count = initialCount;
function innerFunction() {
count++;
console.log(count);
}
return innerFunction;
}
let closure = outerFunction(10);
closure(); // Output: 11
Discussion
それは
const
だけでは?変数宣言の無い言語である python と比べるなら 同じく 変数宣言の無い言語である php と比べても面白いかもしれませんね。
コメントありがとうございます。おっしゃる通りですね。文章から削除させていただきます。
今phpを扱っていないので記述はしませんでしたが興味深い着目点を提示していただいたのでいつか書ければと思います!