我猜这种模式是最新的流行趋势,但我不理解其中的优点以及作用域的影响。
该模式:
(function(window, document, undefined){
window.MyObject = {
methodA: function() { ... },
methodB: function() { ... }
};
})(window, document)
关于这个问题,我有几个疑问。
封装对象是否有特殊优势?
为什么要传入 window 和 document ,而不是直接访问它们?
为什么要传入 undefined
?
将我们创建的对象直接附加到 window 上是一个特别好的主意吗?
我习惯使用我称之为 Crockford 风格的 JavaScript 封装(因为我从 Douglas Crockford 的 JavaScript 视频中得到了它)。
NameSpace.MyObject = function() {
// Private methods
// These methods are available in the closure
// but are not exposed outside the object we'll be returning.
var methodA = function() { ... };
// Public methods
// We return an object that uses our private functions,
// but only exposes the interface we want to be available.
return {
methodB: function() {
var a = methodA();
},
methodC: function() { ... }
}
// Note that we're executing the function here.
}();
这两种模式中,有一种功能上比另一种更好吗?第一种是第二种的进化版本吗?