2017年9月2日 星期六

[JavaScript] Scope: Global Variable / Local Variable

  • Javascript 變數分為
    • Global Variable:能夠在函式內或函式外宣告,可於整個網頁範圍內調用,所以整個網頁中雖然可有無數個不同名稱 Global Variable,但僅會有一個獨立 Global Variable 名稱,若名稱重覆則會覆蓋變數值,網頁關閉時,Global Variable 亦失效
    • Local Variable:每個不同的函式可有相同 Local Variable 變數名稱,函式間 Local Variable 互不干涉,也無法在函式外其他地方調用,函式結束工作後,Local Variable 亦失效
    • 差異在於宣告的位置、方式以及調用區域的不同,使用全域變數的好處在於調用方便,但有的時候在特定函式中,也許有獨立運作的 script 會用到區域變數,以確保不影響到整個程式的運作,以下為這兩種變數範例應用
  • A globally-scoped variable

// global scope
var a = 1;

function case1() {
  console.log(a);
}

case1();
  • Local scope

var a = 1;

function case2(a) {
    // alerts the given argument, not the global value of '1'
    console.log(a); 
}

// local scope again
function case3() {
  var a = 3;
  console.log(a);
}

case2(2);
case3();
  • Intermediate: No such thing as block scope in JavaScript (ES5; ES6 introduces let)

var a = 1;

function case4a() {
    if (true) {
        var a = 4;
    }
    // '4', not the global value of '1'
    console.log(a);
}

function case4b() {
    if (true) {
        let a = 4;
    }
    // '1' because the 'let' keyword uses block scoping
    console.log(a); 
}

case4a();
case4b();
  • Intermediate: Object properties

var a = 1;

function case5() {
    this.a = 5;
}
// '5'
console.log(new case5().a); 
  • Advanced: Closure

var a = 1;

var case6 = (function() {
    var a = 6;

    return function() {
        // JavaScript "closure" means I have access to 'a' in here,
        // because it is defined in the function in which I was defined.
        // '6'
        console.log(a); 
    };
})();

case6();
  • Advanced: Prototype-based scope resolution

var a = 1;

function case7() {
    this.a = 7;
}

// [object].prototype.property loses to
// [object].property in the lookup chain. For example...

// Won't get reached, because 'a' is set in the constructor above.
case7.prototype.a = -1;

// Will get reached, even though 'b' is NOT set in the constructor.
case7.prototype.b = 8;
// '7'
console.log(new case7().a);
// '8'
console.log(new case7().b);
  • Global+Local: An extra complex Case
var x = 5;

(function() {
    console.log(x);
    var x = 10;
    console.log(x);
})();
// This will print out undefined and 10 rather than 5 and 10 since 
// JavaScript always moves variable declarations (not initializations) 
// to the top of the scope, making the code equivalent to:
var x = 5;

(function() {
    var x;
    console.log(x);
    x = 10;
    console.log(x);
})();
  • Catch clause-scoped variable
// This will print out 5, 6, 5. 
// Inside the catch clause e shadows global and local variables. 
// But this special scope is only for the caught variable. 
// If you write var f; inside the catch clause, then it's exactly the same as 
// if you had defined it before or after the try-catch block.
var e = 5;
console.log(e);
try {
    throw 6;
} catch (e) {
    console.log(e);
}
console.log(e);


沒有留言:

張貼留言