使用(函数(窗口,文档,未定义){...})(窗口,文档)赋予什么优势?
我想使用这种模式是新的热点,但我不明白它的优点是什么,我不理解范围的含义。
模式:
(function(window, document, undefined){
window.MyObject = {
methodA: function() { ... },
methodB: function() { ... }
};})(window, document)所以我对此有几个问题。
封装像这样的对象有什么特别的优势吗?
为什么窗口和文档被输入而不是正常访问?
为什么undefined要传递这个?
将我们正在创建的对象直接附加到窗口是一个特别好的主意吗?
我已经习惯了我称之为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.}();其中一种模式在功能上优于另一种吗?第一个是另一个的演变吗?
冉冉说
长风秋雁
相关分类