Discuss / Python / 这就涉及到作用域的问题了...和JS还不一样= =

这就涉及到作用域的问题了...和JS还不一样= =

Topic source

lostexin

#1 Created at ... [Delete] [Delete and Lock User]

闭包有个特性:被闭包函数引用的外层函数的参数以及局部变量会保存在内存中,直到闭包函数被销毁

Python作用域可以参考菜鸟教程(ctrl + f搜索global就会找到你想要的答案):https://www.runoob.com/python3/python3-function.html

def createCounter():
    i = 0
    def counter():
        nonlocal i
        i += 1
        return i
    return counter
// JavaScript
const createCounter = () => {
	let i = 0;
	return () => ++i;
}

counterA = createCounter();

console.log(counterA(), counterA(), counterA(), counterA(), counterA())
// 1 2 3 4 5

// -------------

counterB = createCounter();
[counterB(), counterB(), counterB(), counterB()] // [1, 2, 3, 4]

  • 1

Reply