私は次のようなパターンで作業しています(疑似例):
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); }
3 つの質問:
- 「プライベート」メソッドが を参照しない場合、
this
それらを「標準」関数 (つまりfunction _imPrivate() { ... }
、たとえば) にする必要がありますか? 質問する理由:を参照するメソッドがいくつかありますがthis
、パブリック アクセスを許可したくありません。参照しない「ユーティリティ」メソッドもいくつかありますthis
...参照するメソッドthis
は、(モジュールパターンのコンテキストで) 標準関数にすることができますか? - 誰かが
setThis
変数のセッターを実装する方法の例を提供できますか? - 上記のコードに改善の余地はありますか?