它们都在完成同样的事情,在代码运行时在全局命名空间中创建一个对象。
其中一个不是比另一个更“硬编码”,因为它们都没有进行任何类型的函数原型设计,您可以使用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