2011-09-11 15 views
0

Javascript: Module Patternについてよく聞いたことがあります。しかし、これらの記事のほとんどは静的クラスを作る方法を説明しています。つまり、インスタンスを扱う必要がなく、オブジェクトで作成されたモジュラーパターンを共有したいときです。いくつかのいずれかは、コンストラクタ関数で私にこのパターンを説明することができます。この例を言う:モジュラパターンのコンストラクタ関数を作成する

function Shape(x, y) { 
    this.x= x; 
    this.y= y; 
} 
Shape.prototype.toString= function() { 
    return 'Shape at '+this.x+', '+this.y; 
}; 
function Circle(x, y, r) { 
    Shape.call(this, x, y); // invoke the base class's constructor function to take co-ords 
    this.r= r; 
} 
Circle.prototype= new Shape(); 
Circle.prototype.toString= function() { 
    return 'Circular '+Shape.prototype.toString.call(this)+' with radius '+this.r; 
} 

私は、モジュール式のパターンに変換する方法を教えてください。モジュラーパターンの方法でそれを使用する利点はありますか?

答えて

0

モジュールパターンを使用する利点はカプセル化です。

たぶんこれが何をしたいです:

function Shape(x, y) { 
    function toString() { 
     return 'Shape at '+x+', '+y; 
    } 
    return { toString: toString }; 
} 
var shape = Shape(1, 2); 
shape.toString(); 

これは、しかし、明確な利点を持っていません。これはあなたのプライベート変数を作成することができますが、あなたはあまりにも古典的なコンストラクタでそれを行うことができます:

function Shape(x, y) { 
    this.toString = function() { 
     return 'Shape at '+x+', '+y; 
    }; 
}; 

var shape = new Shape(1, 2); 
shape.toString(); 

それともあなたはモジュールに形状やサークルの両方をカプセル化したいと思います。この場合、モジュールからシェイプとサークルを返すだけです。

var Module = (function() { 
    function Shape ... 

    function Circle ... 

    return { Shape: Shape, Circle: Circle }; 
}()); 
var shape = new Module.Shape(1, 2); 
関連する問題