我,看起来像这样(伪例子)的模式工作:Javascript模块模式:何时使用私有方法? getter/setter方法?需要改进的地方?
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
变量的setter的例子吗? - 您是否看到有改进上述代码的空间?
您可以使用'.call'或'.apply'为任何函数传递上下文。因此,项目#1不完全正确 – zerkms 2012-07-23 22:25:49
您的私有方法是相当公开的。 – Bergi 2012-07-23 22:26:48
为什么你会返回“mq”? – Bergi 2012-07-23 22:27:01