【发布时间】:2018-04-02 12:03:14
【问题描述】:
在 StackOverflow(或其他一些问答网站,我不确定)中有很高的词法范围答案,描述为
function a() {
var x
x = 3
function b() {
x = 4
}
function c(){
var x
b()
}
c()
print(x)
}
一般来说答案是这样的
if(final output is 4):
it is lexical scope
elif(final output is 3):
it's dynamic scope
我做个结论:
-
所以词法作用域与在哪里调用函数无关,而是在哪里定义函数。
如果词法范围与调用函数的位置有关: b() 在 c() 中调用,最终输出应该是 3
普通变量都遵循词法范围规则
以下是我的代码
let a = "before f()"
function f(){
console.log(a)
}
f() -->output: before f()
a = "before b() after f()"
f() -->output: before b() after f()
我的问题:
为什么第二次调用 f() 是 before b() after f(),而不是 before f()?
这是我认为的过程
invoking f() the second time
go to function definition and try to find value of a
go to lexical scope where it's out and up to function definition
find a = "before f()"
【问题讨论】:
-
您可以添加指向您所指问题的链接吗?
-
@Oliver Charlesworth 我尝试在 StackOverflow 中搜索,但找不到。我不确定它在哪里,因为它很久以前就记录在我的笔记本上