【问题标题】:JS Global/Function Scope UnderstandingJS全局/函数作用域理解
【发布时间】:2015-04-20 10:30:31
【问题描述】:

我目前正在学习 Javascript 课程,我希望得到一些帮助,以了解作用域的工作原理。我们已经讨论过全局范围、函数范围、课堂提升等主题,但我正在努力将它们放在一起。所以我特别关注的问题包括弄清楚以下代码输出了什么:

x = 1;
var a = 5;
var b = 10;
var c = function (a, b, c) {
    document.write(x);
    document.write(a);
    var f = function (a, b, c) {
        b = a;
        document.write(b);
        b = c;
        var x = 5;
    }
    f(a, b, c);
    document.write(b);
    var x = 10;
}
c(8, 9, 10);
document.write(b); 
document.write(x);

现在我们的解决方案是代码将打印出 undefined 8 8 9 10 1

我需要一些帮助来了解这究竟是如何发生的。具体来说,我不明白 b 的值如何根据我们正在查看的语句而变化。如果有人可以为我一步一步地完成整个过程,将不胜感激。 谢谢!

【问题讨论】:

  • 你认为会发生什么?究竟是什么意外?

标签: javascript global-variables scope hoisting


【解决方案1】:

我对代码做了一些评论,希望它更有意义。要理解的最重要的概念是变量提升和函数范围。 JavaScript 中只有函数作用域。

x = 1;
var a = 5;
var b = 10;
var c = function (a, b, c) {

    /* this `x` refers to the new `x` variable initialized below
     * near the closing function `c` brace.
     * It is undefined because of hoisting, and gets assigned
     * a value where it was initialized below.
     */
    console.log(x); // undefined

    /* this `a` refers to this `a` parameter,
     * because it is within this function `c` scope.
     */
    console.log(a);

    var f = function (a, b, c) {

        /* this `b` refers to this `b` parameter,
         * because it is within this function `f` scope.
         *
         * this `a` refers to this `a` parameter,
         * because it is within this function `f` scope.
         */
        b = a;
        console.log(b);

         /* this `b` still refers to `b` in this function `f` scope.
          *
          * this `c` refers to this `c` parameter,
          * because it is within this function scope.
          */
        b = c;

        /* this is a new `x` variable because it is
         * with this function `f` scope and there is no parameter `x`.
         */
        var x = 5;
    };

    /* these `a`, `b`, and `c` variables refer to
     * this function `c` parameters.
     */
    f(a, b, c); // f(5, 10, 10)
    console.log(b); // 9

   /* this is a new `x` variable because it is
    * with this function `c` scope and there is no parameter `x`.
    */
    var x = 10;
};

c(8, 9, 10);

/* `a`, `b`, `c`, and `x` have not been touched,
 * because the other `a`,`b`,`c` variables were parameter names,
 * and other `x` variables were initialized within a different scope.
 */
console.log(b); // 10 
console.log(x); // 1

JSBin Demo

【讨论】:

  • 我注意到您在 f(a,b,c) 语句执行到“10”之后说 console.log(b)。你能告诉我我们是如何在输出中得到中间 8 和 9 的吗,在哪一行产生这些以及为什么
  • @DavidW 这显然是一个错误。应该是 9。感谢指出错误。
猜你喜欢
  • 2016-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-06
  • 1970-01-01
相关资源
最近更新 更多