对象是否可以访问外部词法环境?
Do objects have access to outer Lexical Environment?
我试图为 JS fun practice 的 counter(i)
函数找到一个解决方案,结果我得到了这个:
function counter(start) {
let count = start;
return {
up() {
return ++count;
},
down() {
return --count;
},
}
}
let obj = counter(10);
let {up, down} = obj;
console.log(up()); // 11
console.log(down()); // 10
console.log(down()); // 9
console.log(up()); // 10
乍一看我以为会出错,因为对象没有词法环境。我认为 up()
和 down()
都无法访问 count
。但是当我尝试 运行 代码时,它成功了!
我知道 Lexical Environment 是如何工作的,我想知道是否有一种方法可以让对象访问它。
当 counter
函数 returns 对象时,对象与其词法环境之间应该有一个 link 以便 up()
和 down()
可以访问 count
.有这样的吗?
I know how Lexical Environment works, and I wonder if there is a way for objects to access it.
When counter function returns the object there should be a link between the object and its Lexical Environment so that up() and down() can access count. Is there anything like that?
是的。 Javascript 支持 3 种作用域:
- 全球
- 函数
- 阻止
一对花括号 ({...}) 中的任何内容在 Javascript 中形成一个块。块作用域有自己的词法环境。所以从 counter()
返回的对象是一个块,它引用了 counter()
的词法环境,使用它可以访问 count
变量。
函数 up()
和 down()
形成一个闭包,因此即使从全局调用时也可以访问 count
,即在 counter()
的范围之外。
我试图为 JS fun practice 的 counter(i)
函数找到一个解决方案,结果我得到了这个:
function counter(start) {
let count = start;
return {
up() {
return ++count;
},
down() {
return --count;
},
}
}
let obj = counter(10);
let {up, down} = obj;
console.log(up()); // 11
console.log(down()); // 10
console.log(down()); // 9
console.log(up()); // 10
up()
和 down()
都无法访问 count
。但是当我尝试 运行 代码时,它成功了!我知道 Lexical Environment 是如何工作的,我想知道是否有一种方法可以让对象访问它。
当
counter
函数 returns 对象时,对象与其词法环境之间应该有一个 link 以便 up()
和 down()
可以访问 count
.有这样的吗?
I know how Lexical Environment works, and I wonder if there is a way for objects to access it. When counter function returns the object there should be a link between the object and its Lexical Environment so that up() and down() can access count. Is there anything like that?
是的。 Javascript 支持 3 种作用域:
- 全球
- 函数
- 阻止
一对花括号 ({...}) 中的任何内容在 Javascript 中形成一个块。块作用域有自己的词法环境。所以从 counter()
返回的对象是一个块,它引用了 counter()
的词法环境,使用它可以访问 count
变量。
函数 up()
和 down()
形成一个闭包,因此即使从全局调用时也可以访问 count
,即在 counter()
的范围之外。