2

实际上,以下两种模式之间的区别是什么?

一个

mySpace = mySpace || {}
mySpace.isObsolete = function() {};
mySpace.hipsterYear = 2006;

用法:

var iable = mySpace.isObsolete();
var year = mySpace.hipsterYear;

B(即模块模式)

mySpace = (function(){
  var obj = {};
  var someVar = 2012;
  obj.hipsterYear = 2006;
  obj.isObsolete: function() {};
  return obj;
}());

用法:

var iable = mySpace.isObsolete();
var year = mySpace.hipsterYear;

在 B 中,匿名函数创建了一个范围,其中 someVar 不能从外部访问。我想这样的构造在 A 中是不可能的?因此,A 和 B 在创建范围方面有所不同。

命名空间有什么区别?A和B是等价的吗?

4

1 回答 1

4

B is commonly called the 'module pattern' and allows the option to use the object oriented approach of having public and private access to variables and methods, whereas with A everything is public. Douglas Crockford explains it best here.

This is generally a good idea, as using the approach in A allows everything to be vulnerable to interference from other code/coders. This increases the likelihood of obscure bugs emerging if someone (possibly you) decides to take shortcuts.

于 2012-07-17T12:40:36.550 回答