萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 作用域與執行上下文完整指南:從基礎到閉包、bind 應用

核心觀念釐清

  • 作用域:函數基礎,決定變數存取範圍。每次函數調用建立新作用域,獨立互不干擾。
  • 上下文:物件基礎,指 this 指向的物件。由「如何調用函數」決定。
  • 執行上下文:ECMAScript 術語,實指「作用域鏈上的某一層」,非上文的 this 上下文。

變數作用域

  • 全域變數:函數外宣告,生命週期貫穿整個程式,任意處可存取。
  • 區域變數:函數內宣告,僅在該次調用的作用域內有效。
  • 無區塊作用域(ES5):if/for/while 區塊內的 var 變數會「提升」至函數頂部。
    ES6 let/const 提供真正區塊作用域。

this 上下文決定規則

調用方式this 指向範例
物件方法調用該物件obj.foo() → this = obj
建構函數 new新建立的實例new Foo() → this = 實例
普通函數調用全域物件(瀏覽器為 window)foo() → this = window
嚴格模式普通調用undefined"use strict"; foo() → this = undefined
call/apply/bind指定的第一個參數fn.call(obj) → this = obj

執行上下文堆疊與作用域鏈


function first(){ second(); }
function second(){ third(); }
function third(){ fourth(); }
function fourth(){ /* do something */ }
first();

呼叫堆疊(作用域鏈頂→底):fourth → third → second → first → global。
尋找變數:從當前執行上下文變數物件開始,沿作用域鏈向上直到全域。同名變數,越內層優先級越高。

閉包

當內部函數在外部函數返回後仍被引用,形成閉包,保有對外部函數變數、參數、函數宣告的存取權。


function foo(){
    var local = 'private';
    return function bar(){ return local; };
}
var getLocal = foo();
getLocal(); // "private" —— 仍能存取已返回的 foo 作用域變數

模組模式


var Module = (function(){
    var privateProp = 'foo';
    function privateMethod(){ /* ... */ }
    return {
        publicProp: '',
        publicMethod: function(){ /* ... */ },
        privilegedMethod: function(){ privateMethod(); }
    };
})();

IIFE(立即調用函數表達式)


(function(window){
    var a = 'foo';
    window.Module = { public: function(){ /* ... */ } };
})(this);

保護全域命名空間,常用於程式庫封裝。

call / apply / bind


function user(first, last, age){ /* ... */ }
user.call(window, 'John', 'Doe', 30);   // 參數列表
user.apply(window, ['John', 'Doe', 30]); // 參數陣列

ES5 bind 實作與應用


if (!Function.prototype.bind) {
    Function.prototype.bind = function(){
        var fn = this, context = arguments[0],
            args = Array.prototype.slice.call(arguments, 1);
        return function(){
            return fn.apply(context, args);
        };
    };
}

// 事件處理綁定 this
function MyClass(){
    this.el = document.createElement('div');
    this.el.addEventListener('click', this.onClick.bind(this), false);
}
MyClass.prototype.onClick = function(e){ /* this 正確指向實例 */ };

類陣列轉陣列技巧


// arguments、NodeList 非真陣列,但可借用陣列方法
var argsArr = Array.prototype.slice.call(arguments, 1);
var divsArr = Array.prototype.slice.call(document.getElementsByTagName('div'));

總結

  1. 作用域 = 變數查找規則(靜態/詞法);上下文 = this 指向(動態/執行時)。
  2. 閉包 = 函數 + 其詞法環境的引用,實現資料封裝與狀態保持。
  3. 善用 bind 固定回調上下文,避免事件處理器 this 指向錯誤。
  4. 理解作用域鏈與執行堆疊,有助除錯變數遮蔽與記憶體洩漏。
copyright © 萬盛學電腦網 all rights reserved