gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
閉包的範例
- User
閉包的範例
- Assistant
閉包是指在一個函數內部定義的函數,這個內部函數可以訪問外部函數的變數,即使外部函數已經執行完成。以下是一些閉包的範例,使用 JavaScript 和 Python 提供不同語言的示例。
JavaScript 範例
javascriptfunction outerFunction(x) { return function innerFunction(y) { return x + y; // innerFunction 可以訪問外部函數 outerFunction 的變數 x }; } const addFive = outerFunction(5); // outerFunction 返回的 innerFunction 被賦值給 addFive console.log(addFive(10)); // 輸出 15, 因為 5 + 10 = 15Python 範例
pythondef outer_function(x): def inner_function(y): return x + y # inner_function 可以訪問 outer_function 的變數 x return inner_function add_five = outer_function(5) # outer_function 返回的 inner_function 被賦值給 add_five print(add_five(10)) # 輸出 15, 因為 5 + 10 = 15這些範例顯示了如何使用閉包來封裝變數,使其在內部函數中可用。這種特性使得閉包在許多編程範疇中非常有用,例如在實現私有變數或函數計算狀態時。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.