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
该关键字允许您从函数内部访问和更新全局变量。这使得无需编写类就可以在函数内管理值。
count = 0
def outer_function():
global count
count += 1
print(count)
outer_function() # Output: 1
outer_function() # Output: 2
JavaScript 闭包
- 如何定义:
在一个函数内部定义另一个函数,内部函数引用外部函数的变量。这也可以通过将箭头函数或者函数直接写进return来实现。
function outerFunction(text) {
function innerFunction() {
console.log(text);
}
return innerFunction;
}
var closure = outerFunction('Hello, JavaScript!');
closure(); // Output: Hello, JavaScript!
- 参数代入:
Pythonnonlocal
需要关键字,而 JavaScript 则不需要。const
使用时重新代入值。
function outerFunction(count) {
function innerFunction() {
count++;
console.log(count);
}
return innerFunction;
}
var closure = outerFunction(10);
closure(); // Output: 11
- 定义一个计数变量:
在外部函数中定义一个变量并在闭包内使用它。
function outerFunction(initialCount) {
let count = initialCount;
function innerFunction() {
count++;
console.log(count);
}
return innerFunction;
}
let closure = outerFunction(10);
closure(); // Output: 11