【问题标题】:why the value of variable doesn't show as expected?为什么变量的值没有按预期显示?
【发布时间】: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

我做个结论:

  1. 所以词法作用域与在哪里调用函数无关,而是在哪里定义函数。

    如果词法范围与调用函数的位置有关: b() 在 c() 中调用,最终输出应该是 3

  2. 普通变量都遵循词法范围规则


以下是我的代码

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 中搜索,但找不到。我不确定它在哪里,因为它很久以前就记录在我的笔记本上

标签: javascript lexical-scope


【解决方案1】:

范围确定使用哪个变量,并取决于函数的声明位置。

所使用的将是您从中读取的那个变量当时的值(即调用函数时)。

【讨论】:

  • 是否有任何方法可以使function c() 变量var x 在不使用return 语句的情况下也受到影响并在print() 语句中返回。只需将当前的代码转换var 关键字混为一谈这里那里?
  • 作用域为函数c,因此不受函数c之外的代码影响。
  • 如果函数 b 的主体也嵌套在函数 c 中,则 print 语句将记录 undefined 但函数 c 的变量将获得 b 设置的新值...对吗?
猜你喜欢
  • 2020-09-04
  • 1970-01-01
  • 1970-01-01
  • 2020-04-07
  • 2022-01-18
  • 2020-02-16
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
相关资源
最近更新 更多