萬盛學電腦網

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

JavaScript 匿名函數與 IIFE 完整指南:封裝、模塊化、插件開發核心模式

匿名函數基礎

// 函數表達式 (匿名函數賦值給變量)
var add = function(a, b) { return a + b; };

// 立即調用函數表達式 (IIFE) - 核心模式
(function() {
    // 這裡是獨立作用域
    var privateVar = 'secret';
    window.publicAPI = { get: function() { return privateVar; } };
})();

console.log(publicAPI.get()); // 'secret'
// console.log(privateVar); // ReferenceError: 不可訪問

IIFE 兩種寫法

// 1. 括號包裹函數表達式 (推薦,語義清晰)
(function() { /* code */ }());

// 2. 括號包裹整個調用表達式
(function() { /* code */ })();

// 其他變體 (利用運算符優先級)
!function() {}();
+function() {}();
~function() {}();
void function() {}();
new function() {}(); // 返回實例

核心用途

1. 創建私有作用域 (模塊模式)

var Counter = (function() {
    var count = 0; // 私有變量
    
    function increment() { count++; }
    function decrement() { count--; }
    function get() { return count; }
    
    // 公開 API
    return {
        increment: increment,
        decrement: decrement,
        get: get
    };
})();

Counter.increment();
Counter.increment();
console.log(Counter.get()); // 2
// count 完全不可從外部訪問

2. jQuery 插件開發模式

;(function($, window, document, undefined) {
    // undefined 參數防止被篡改 (ES3 環境)
    // $ 別名安全,避免衝突
    
    var pluginName = 'myPlugin';
    var defaults = {color: 'blue', speed: 300};
    
    function Plugin(element, options) {
        this.element = element;
        this.settings = $.extend({}, defaults, options);
        this.init();
    }
    
    Plugin.prototype = {
        init: function() {
            $(this.element).css('color', this.settings.color);
        },
        destroy: function() {
            $.removeData(this.element, pluginName);
        }
    };
    
    // 掛載到 $.fn
    $.fn[pluginName] = function(options) {
        return this.each(function() {
            if (!$.data(this, pluginName)) {
                $.data(this, pluginName, new Plugin(this, options));
            }
        });
    };
})(jQuery, window, document);

// 使用
$('#elem').myPlugin({color: 'red'});

3. 傳遞全局對象參數化 (性能/壓縮優化)

(function($, window, document, Math, undefined) {
    // 內部引用 $, window, document, Math 變為局部變量查找
    // 壓縮時可縮短為單字母: function(a,b,c,d,e){...}
    // 避免全局查找開銷
})(jQuery, window, document, Math);

4. 條件加載 / Polyfill 注入

(function() {
    if (!Array.prototype.find) {
        Array.prototype.find = function(predicate) {
            if (this == null) throw new TypeError();
            var list = Object(this);
            var len = list.length >>> 0;
            if (typeof predicate !== 'function') throw new TypeError();
            var thisArg = arguments[1];
            for (var i = 0; i < len; i++) {
                if (i in list && predicate.call(thisArg, list[i], i, list)) {
                    return list[i];
                }
            }
            return undefined;
        };
    }
})();

進階模式

UMD (Universal Module Definition)

(function(root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory); // AMD
    } else if (typeof module === 'object' && module.exports) {
        module.exports = factory(require('jquery')); // CommonJS
    } else {
        root.myPlugin = factory(root.jQuery); // 全局變量
    }
}(typeof self !== 'undefined' ? self : this, function($) {
    // 插件核心代碼
    return { version: '1.0.0' };
}));

揭示模塊模式

var MyModule = (function() {
    var privateVar = 0;
    function privateMethod() { console.log('private'); }
    
    function publicMethod() {
        privateMethod();
        console.log('public: ' + ++privateVar);
    }
    
    return {
        publicMethod: publicMethod
    };
})();

常見誤區

  • ❌ function() {}() 語法錯誤 (函數聲明不能直接調用)
  • ❌ 循環中創建閉包捕獲變量錯誤 (用 IIFE 或 let 解決)
  • ✅ 分號前置 ;(function(){})() 防止前文無分號導致合併錯誤
  • ✅ 參數化全局依賴,利於壓縮與測試

ES6 Modules 時代的定位

ES6 import/export 解決了模塊化標準化,IIFE 仍用於:

  • 非模塊化腳本的作用域隔離
  • Polyfill/Shim 注入
  • 構建工具生成的包裹代碼 (Webpack/Rollup bundle wrapper)
  • 動態腳本加載回調包裹
copyright © 萬盛學電腦網 all rights reserved