🗂

PythonのクロージャとJavaScriptのクロージャ、実装の違い

2025/02/07に公開
2

Pythonのクロージャ

  1. 定義方法: 関数の中で別の関数を定義し、内側の関数が外側の関数の変数を参照する。
def outer_function(text):
    def inner_function():
        print(text)
    return inner_function

closure = outer_function('Hello, Python!')
closure()  # Output: Hello, Python!
  1. 再代入の制限: nonlocalキーワードが必要。
def outer_function(count):
    def inner_function():
        nonlocal count
        count += 1
        print(count)
    return inner_function

closure = outer_function(10)
closure()  # Output: 11
  1. globalキーワードの使い方: globalキーワードで関数内からグローバル変数を参照および更新。これによりクラスを書かずに関数の中だけで値を管理することが可能になる。
count = 0

def outer_function():
    global count
    count += 1
    print(count)

outer_function()  # Output: 1
outer_function()  # Output: 2

JavaScriptのクロージャ

  1. 定義方法: 関数の中で別の関数を定義し、内側の関数が外側の関数の変数を参照する。returnのなかにアロー関数やfunctionを直接書き込むことでも実装は可能。
function outerFunction(text) {
    function innerFunction() {
        console.log(text);
    }
    return innerFunction;
}

var closure = outerFunction('Hello, JavaScript!');
closure();  // Output: Hello, JavaScript!
  1. 再代入の制限: Pythonではnonlocalキーワードが必要だが、JavaScriptでは不要。constを使用する場合は再代入に制限がかかる。
function outerFunction(count) {
    function innerFunction() {
        count++;
        console.log(count);
    }
    return innerFunction;
}

let closure = outerFunction(10);
closure();  // Output: 11
  1. count変数の定義: 外部関数で変数を定義し、クロージャ内で使用。
function outerFunction(initialCount) {
    let count = initialCount;

    function innerFunction() {
        count++;
        console.log(count);
    }

    return innerFunction;
}

let closure = outerFunction(10);
closure();  // Output: 11

Discussion

junerjuner

letconst を使用する場合は再代入に制限がかかる。

それは const だけでは?


変数宣言の無い言語である python と比べるなら 同じく 変数宣言の無い言語である php と比べても面白いかもしれませんね。

tac-tac-gotac-tac-go

それは const だけでは?

コメントありがとうございます。おっしゃる通りですね。文章から削除させていただきます。

変数宣言の無い言語である python と比べるなら 同じく 変数宣言の無い言語である php と比べても面白いかもしれませんね。

今phpを扱っていないので記述はしませんでしたが興味深い着目点を提示していただいたのでいつか書ければと思います!