1 回答

TA貢獻1725條經驗 獲得超8個贊
在這里解決這個問題的最簡單方法如下:
轉換shapeModel
為類?;蛘吒咏惶谜n。它已經是你調用的構造函數new
,所以你不妨使用原型繼承,讓你的生活更輕松。
ShapeModel
用大寫字母命名S
。這是構造函數的公認約定。分配您獲得的所有構造函數參數
this
,以便您以后可以重新使用它們。將
fullShape
方法移至原型。作為一個優勢,您不需要為您創建fullShape
的每一個函數提供一個函數ShapeModel
- 內存中只有一個函數,并且所有ShapeModel
s 都共享它。如果你有很多這些,它會減少內存占用。添加一個
.clone()
方法,以便您可以從舊實例創建新實例。通過這種方式,很容易維護如何克隆東西的邏輯,并且如果你真正需要的只是克隆一種類型的對象,你不需要想出一個很難適應的超級通用克隆機制。
一旦完成,您就有了一個簡單且可重用的構造函數。由于您可以獲取任何對象并調用.clone()
它,因此制作副本的方法很簡單:
shapeArray.map(function(model) {
return model.clone();
});
這是整個事情的樣子:
function ShapeModel(c, fshape, circle, misc) {
this.shapeColour = c;
this.fshape = fshape;
this.circle = circle;
this.misc = misc;
this.startX = 200;
this.startY = 200;
this.thickness = 6;
return newElement;
}
ShapeModel.prototype.fullShape = function() {
this.fshape(this);
this.circle(this);
this.misc(this);
}
ShapeModel.prototype.clone = function() {
return new ShapeModel(this.shapeColour, this.fshape, this.circle, this.misc);
}
var shapeArray = [
new ShapeModel("#ff0", FShape1, circleSegment, miscShape1),
new ShapeModel("#f00", FShape1, circleHollow, miscShape1),
new ShapeModel("#000", FShape1, circleSegment, miscShape2),
new ShapeModel("#08f", FShape2, circleSegment, miscShape1),
new ShapeModel("#060", FShape2, circleHollow, miscShape1),
new ShapeModel("#007", FShape2, circleSegment, miscShape2),
new ShapeModel("#0f7", FShape1, circleHollow, miscShape2),
new ShapeModel("#888", FShape2, circleHollow, miscShape2)
];
var shapeList = shapeArray.map(function(model) {
return model.clone;
});
添加回答
舉報