它們都在完成同樣的事情,在代碼運行時在全局命名空間中創建一個對象。
其中一個不是比另一個更「硬編碼」,因爲它們都沒有進行任何類型的函數原型設計,您可以使用new關鍵字創建對象的克隆。在我看來,這只是一個偏好問題。
舉例來說,jQuery不會一個類似於後者:
(function(window, undefined) {
// Use the correct document accordingly with window argument (sandbox)
var document = window.document;
var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function(selector, context) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init(selector, context, rootjQuery);
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
...
但原型JS庫不前:
var Prototype = {
Version: '1.6.1',
Browser: (function(){
var ua = navigator.userAgent;
var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]';
return {
IE: !!window.attachEvent && !isOpera,
Opera: isOpera,
WebKit: ua.indexOf('AppleWebKit/') > -1,
Gecko: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') === -1,
MobileSafari: /Apple.*Mobile.*Safari/.test(ua)
}
})(),
...
我不知道有任何理由一個是優於另一個,或者他們完成不同的任務(在窗口命名空間中創建應用程序對象)。
我個人更喜歡第一個,因爲它沒有「硬編碼」對象 – mplungjan 2011-02-02 06:38:38