// 函數表達式 (匿名函數賦值給變量)
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: 不可訪問
// 1. 括號包裹函數表達式 (推薦,語義清晰)
(function() { /* code */ }());
// 2. 括號包裹整個調用表達式
(function() { /* code */ })();
// 其他變體 (利用運算符優先級)
!function() {}();
+function() {}();
~function() {}();
void function() {}();
new function() {}(); // 返回實例
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 完全不可從外部訪問
;(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'});
(function($, window, document, Math, undefined) {
// 內部引用 $, window, document, Math 變為局部變量查找
// 壓縮時可縮短為單字母: function(a,b,c,d,e){...}
// 避免全局查找開銷
})(jQuery, window, document, Math);
(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;
};
}
})();
(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() {}() 語法錯誤 (函數聲明不能直接調用);(function(){})() 防止前文無分號導致合併錯誤ES6 import/export 解決了模塊化標準化,IIFE 仍用於: