我正在使用看起来像这样的模式(伪示例):
var FOO = (function(foo) {
var foo = foo || {},
setThis = 'someValue';
//--------------------------------------------------------------------------
//
// Public methods:
//
//--------------------------------------------------------------------------
foo.init = function(bar) {
this.blah = [];
// Constructor stuff here...
};
foo.doSomething = function(bar) {
if (bar) {
this.doSomethingElse();
// Stuff here...
}
};
foo.doSomethingElse = function() {
// Stuff here...
};
//--------------------------------------------------------------------------
//
// Private methods:
//
//--------------------------------------------------------------------------
foo._imPrivate = function() {
// ... stuff here ...
this.blah = xyz; // References this.
};
foo._morePrivate = function(el) {
// No reference to this.
};
foo._otherPrivate = function(el) {
// No reference to this.
};
return foo; // Expose the methods.
}(FOO || {}));
像这样实例化:
window.onload = function() { FOO.init(stuff); }
三个问题:
- 如果我的“私有”方法不引用
this
,我是否应该将它们设为“标准”函数(function _imPrivate() { ... }
例如)?我问的原因:我有一些引用的方法this
,但我不想让它们公开访问;我还有一些不引用的“实用程序”方法this
......引用的方法可以this
是标准函数(在模块模式的上下文中)吗? - 有人可以提供一个示例来说明我将如何为
setThis
变量实现设置器吗? - Do you see any room for improvements in the above code?