萬盛學電腦網

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

個人常用 Global.js 工具庫源碼:命名空間、DOM、事件、語言、Cookie 封裝

整理多年專案萃取的輕量工具庫,採用命名空間模組化,涵蓋 DOM 操作、事件綁定、型別判斷、字串處理、Cookie 管理等高頻功能,無第三方依賴,壓縮後約 3KB。

架構設計

var GLOBAL = {};
GLOBAL.namespace = function(ns) {
  var parts = ns.split('.'), obj = GLOBAL, i = (parts[0] === 'GLOBAL') ? 1 : 0;
  for (; i < parts.length; i++) {
    obj[parts[i]] = obj[parts[i]] || {};
    obj = obj[parts[i]];
  }
};

核心模組速覽

GLOBAL.Dom

  • `get(id|element)`:統一取得元素
  • `getNextNode(node)`:取得下一個元素節點(修正 IE textNode 問題)
  • `setOpacity(node, level)`:跨瀏覽器透明度(IE filter / 標準 opacity)
  • `getElementsByClassName(className, root, tag)`:IE8 相容類別選取

GLOBAL.Event

  • `on(node, type, handler)`:統一 `addEventListener` / `attachEvent`
  • `stopPropagation(e)`:跨瀏覽器停止冒泡
  • `getEventTarget(e)`:統一 `target` / `srcElement`

GLOBAL.Lang

  • `trim(str)`:去除首尾空白
  • `isNumber(val)` / `isString` / `isBoolean` / `isFunction` / `isNull` / `isUndefined` / `isEmpty` / `isArray`:型別檢查
  • `extend(subClass, superClass)`:原型鏈繼承輔助(ES5 風格)

GLOBAL.Cookie

  • `set(name, value, expires, path, domain, secure)`
  • `get(name)`
  • `del(name, path, domain, secure)`

使用範例

<script src="global.js"></script>
<script>
GLOBAL.namespace('MyApp.Utils');
MyApp.Utils.formatDate = function(d) { ... };

// DOM
var btn = GLOBAL.Dom.get('submitBtn');
GLOBAL.Event.on(btn, 'click', function(e) {
  var target = GLOBAL.Event.getEventTarget(e);
  GLOBAL.Dom.setOpacity(target, 50);
});

// Cookie
GLOBAL.Cookie.set('token', 'abc123', 7); // 7 天
var token = GLOBAL.Cookie.get('token');

現代化建議

  • 改用 ES Modules:`export const Dom = { ... }`
  • 型別檢查改用 `Object.prototype.toString.call` 或 `Array.isArray` 等標準 API
  • 事件系統改用 `EventTarget` 或輕量發布訂閱
  • Cookie 改用 `js-cookie` 或原生 `document.cookie` 封裝
  • 整合 TypeScript 定義檔(`.d.ts`)提供型別提示

完整源碼結構(節錄)

var GLOBAL = {};
GLOBAL.namespace = function(str) { ... };

// Dom
GLOBAL.namespace('Dom');
GLOBAL.Dom.get = function(node) { ... };
GLOBAL.Dom.getNextNode = function(node) { ... };
GLOBAL.Dom.setOpacity = function(node, level) { ... };
GLOBAL.Dom.getElementsByClassName = function(str, root, tag) { ... };

// Event
GLOBAL.namespace('Event');
GLOBAL.Event.stopPropagation = function(e) { ... };
GLOBAL.Event.getEventTarget = function(e) { ... };
GLOBAL.Event.on = function(node, eventType, handler) { ... };

// Lang
GLOBAL.namespace('Lang');
GLOBAL.Lang.trim = function(ostr) { return ostr.replace(/^\s+|\s+$/g, ''); };
GLOBAL.Lang.isNumber = function(s) { return !isNaN(s); };
// isString, isBoolean, isFunction, isNull, isUndefined, isEmpty, isArray ...
GLOBAL.Lang.extend = function(subClass, superClass) {
  var F = function(){}; F.prototype = superClass.prototype;
  subClass.prototype = new F();
  subClass.prototype.constructor = subClass;
  subClass.superclass = superClass.prototype;
};

// 便捷別名
function $(node) { return GLOBAL.Dom.get(node); }
copyright © 萬盛學電腦網 all rights reserved