私は一般に、make-an-anonymous-function-then-call-itというパターンに従います。基本的には、内部スコープを作成し、インタフェースを含む単一のオブジェクトを返します。関数スコープ内にすべて閉じ込められているので、エスケープするものはありません。ここではjQueryを使用した例です。このすべてのコードが実行した後
var FancyWidget = (function($) {
// jQuery is passed as an argument, not referred to directly
// So it can work with other frameworks that also use $
// Utility functions, constants etc can be written here
// they won't escape the enclosing scope unless you say so
function message(thing) {
alert("Fancy widget says: " + thing);
}
// Make a simple class encapsulating your widget
function FancyWidget(container) {
container = $(container); // Wrap the container in a jQuery object
this.container = container; // Store it as an attribute
var thisObj = this;
container.find("#clickme").click(function() {
// Inside the event handler, "this" refers to the element
// being clicked, not your FancyWidget -- so we need to
// refer to thisObj instead
thisObj.handleClick();
});
}
// Add methods to your widget
FancyWidget.prototype.handleClick = function() {
this.container.find("#textbox").text("You clicked me!");
message("Hello!");
};
return FancyWidget; // Return your widget class
// Note that this is the only thing that escapes;
// Everything else is inaccessible
})(jQuery);
今、あなたはあなたがしてインスタンス化できる一つのクラス、FancyWidget
、で終わります。
このように複数のクラスを定義することもできます。代わりにreturn FancyWidget
を使用しての、あなたの代わりに、オブジェクトリテラルを返すことができます。
return {
FancyWidget: FancyWidget,
Frobnicator: Frobnicator,
// Nested namespaces!
extra: {
thing: thing,
blah: blah
}
};
http://addyosmani.com/blog/essential-js-namespacing/とhttp://dustindiaz.com/namespace-your-javascript/ – naveen
"関数のラッピング関数"はまったくハックしません。ハスケルのプログラマーはいつもそれをやります。 –
私はそれ以来、関数型プログラミングとクロージャーを読んできました。それはOOPの考え方の変化のちょっとしたものなので、ちょっと見た目がちょっと変わって見えるかもしれません。 – diggingforfire