原文展示的經典錯誤:在 `$(document).ready()` 內部用 `var t = new FunctionTest()` 宣告實例,導致 `t` 成為區域變數,外部 `onclick="t.AlertTest()"` 找不到 `t`,拋出 ReferenceError: t is not defined。
var text = "test";
var t = new FunctionTest(text); // 錯誤:#btnSave 尚未存在
function FunctionTest(text) {
var alertText = text;
$("#btnSave").click(function() { alertTestInner(); }); // 失敗:元素不存在
this.AlertTest = function() { alert(alertText); };
function alertTestInner() { alert(alertText); }
}
$(document).ready(function() {
var t = new FunctionTest("test"); // t 是區域變數!
});
<button onclick="t.AlertTest()">取消</button> // ReferenceError: t is not defined
var t; // 全域宣告
$(document).ready(function() {
t = new FunctionTest("test"); // 賦值給全域變數
});
function FunctionTest(text) {
var alertText = text; // 私有變數 (閉包捕獲)
$("#btnSave").click(function() {
alertTestInner(); // 正常:click 事件在 ready 後觸發,元素已存在
});
this.AlertTest = function() { // 公開方法
alert(alertText);
};
function alertTestInner() { // 私有方法
alert(alertText);
}
}
// var 函式作用域 + 提升
function demo() {
console.log(x); // undefined (非 ReferenceError)
var x = 10;
// 等同於:
// var x;
// console.log(x);
// x = 10;
}
// let/const 區塊作用域 + 暫時性死區 (TDZ)
function demo2() {
// console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 20;
}
function createCounter() {
var count = 0; // 自由變數
return function() { // 內部函式
count++; // 參考自由變數
return count;
};
}
var counter1 = createCounter();
var counter2 = createCounter();
counter1(); // 1
counter1(); // 2
counter2(); // 1 (獨立閉包環境)
// ❌ 錯誤:var 無區塊作用域,所有函式共享同一個 i
for (var i = 0; i < 3; i++) {
setTimeout(function() { console.log(i); }, 100);
}
// 輸出:3, 3, 3
// ✅ 正確 1:IIFE 建立新作用域
for (var i = 0; i < 3; i++) {
(function(i) {
setTimeout(function() { console.log(i); }, 100);
})(i);
}
// 輸出:0, 1, 2
// ✅ 正確 2:let 區塊作用域 (ES6+)
for (let i = 0; i < 3; i++) {
setTimeout(function() { console.log(i); }, 100);
}
// 輸出:0, 1, 2
// ✅ 正確 3:bind 傳遞參數
for (var i = 0; i < 3; i++) {
setTimeout(console.log.bind(console, i), 100);
}
var Module = (function() {
// 私有狀態
var privateVar = 0;
var privateData = [];
// 私有方法
function privateMethod() {
console.log("內部邏輯", privateVar);
}
// 公開介面
return {
publicVar: "公開屬性",
increment: function() {
privateVar++;
privateMethod();
return privateVar;
},
getData: function() {
return privateData.slice(); // 返回副本防篡改
},
addData: function(item) {
privateData.push(item);
}
};
})();
// 使用
Module.increment(); // 1
Module.increment(); // 2
Module.addData("item1");
console.log(Module.getData()); // ["item1"]
// Module.privateVar // undefined (無法存取)
// module-core.js
var Module = (function($, undefined) {
var _config = { apiBase: "/api" };
function _ajax(options) {
return $.ajax($.extend({}, {
url: _config.apiBase + options.url,
dataType: "json"
}, options));
}
return {
config: function(key, val) {
if (val !== undefined) _config[key] = val;
return _config[key];
},
ajax: _ajax
};
})(jQuery);
// module-extra.js (擴充)
var Module = (function(mod, $, undefined) {
mod.getUser = function(id) {
return mod.ajax({ url: "/users/" + id });
};
return mod;
})(Module || {}, jQuery);
// utils/math.js
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export function multiply(a, b) { return a * b; }
// utils/string.js
export function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
// main.js
import { PI, add } from './utils/math.js';
import { capitalize } from './utils/string.js';
import * as MathUtils from './utils/math.js';
console.log(add(1, 2)); // 3
console.log(MathUtils.PI); // 3.14159
原文遇到動態生成的「取消」按鈕無法用 jQuery 綁定,改用 `onclick="t.AlertTest()"` 內聯事件。現代最佳實踐:**事件委派**
// ❌ 錯誤:動態新增的元素無綁定
$("#container .btn-cancel").click(function() { ... });
// ✅ 正確:委派給靜態父容器
$("#container").on("click", ".btn-cancel", function() {
// this 指向觸發事件的 .btn-cancel 元素
var id = $(this).data("id");
handleCancel(id);
});
// 原生 JS 實現 (無 jQuery 依賴)
document.getElementById("container").addEventListener("click", function(e) {
var target = e.target.closest(".btn-cancel");
if (target) {
var id = target.dataset.id;
handleCancel(id);
}
});
<button class="btn-cancel" data-id="123" data-action="delete">取消</button>
$("#container").on("click", ".btn-cancel", function() {
var $btn = $(this);
var id = $btn.data("id");
var action = $btn.data("action");
handleAction(id, action);
});
function createCancelHandler(id, extraData) {
return function(event) {
// 這裡可存取 id, extraData (閉包)
console.log("取消 ID:", id, "額外:", extraData);
// 異步操作...
};
}
// 動態生成時綁定
var handler = createCancelHandler(itemId, { source: "grid" });
$dynamicBtn.on("click", handler);
// 移除時需保留引用
$dynamicBtn.off("click", handler);
// 觸發端
$dynamicBtn.on("click", function() {
$(this).trigger("custom:cancel", { id: 123, reason: "user_cancel" });
});
// 監聽端 (靜態父層)
$("#container").on("custom:cancel", function(e, data) {
console.log("收到取消:", data.id, data.reason);
});
// 1. 狀態管理模組
var StateManager = (function() {
var state = { user: null, permissions: [] };
return {
setUser: function(u) { state.user = u; },
getUser: function() { return state.user; },
hasPermission: function(p) { return state.permissions.includes(p); }
};
})();
// 2. UI 控制模組
var UIController = (function() {
function bindEvents() {
$("#container").on("click", ".btn-action", function() {
var action = $(this).data("action");
ActionHandler.execute(action, $(this).data());
});
}
return { init: bindEvents };
})();
// 3. 業務動作處理器
var ActionHandler = {
execute: function(action, data) {
var handler = this[action];
if (typeof handler === "function") {
handler.call(this, data);
}
},
delete: function(data) {
if (!StateManager.hasPermission("delete")) {
LG.showError("無刪除權限");
return;
}
if (confirm("確定刪除?")) {
api.delete(data.id).then(refreshGrid);
}
},
export: function(data) {
window.open("/export?" + $.param(data));
}
};
// 4. 入口初始化
$(function() {
UIController.init();
// 載入初始資料...
});
JavaScript 封裝核心在於**管理作用域與生命週期**:
this 丟失 → 用箭頭函式、.bind()、或 var self = thislet、IIFE、或 .bind().on() / addEventListener)data-* 屬性、閉包工廠、自訂事件現代專案請直接使用 **ES6 Modules** 配合建構工具,避免手動管理全域命名空間與腳本載入順序。