簡體   English   中英

JS全局/功能范圍理解

[英]JS Global/Function Scope Understanding

我目前正在學習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);

現在,我們擁有的解決方案是代碼將打印出未定義的8 8 9 10 1

我需要一些幫助來了解這是如何發生的。 具體來說,我不了解b的值如何根據我們正在查看的語句而變化。 如果有人能為我逐步完成整個過程,將不勝感激。 謝謝!

我對代碼進行了注釋,因此希望它更有意義。 要理解的最重要概念是變量提升和功能范圍。 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演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM