2011-09-11 39 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);