我有一個卡類:最佳設計實踐分開常見的代碼?
function Card() {
this.image = new Image();
this.x = 0;
this.y = 400;
this.initialX = 0;
this.initialY = 0;
this.scaleFactor = 4;
this.setImage = function(ii){
this.image.src = ii;
};
this.getWidth = function(){
if (this.image == null){
return 0;
}
return this.image.width/this.scaleFactor;
}
this.getHeight = function(){
if (this.image == null){
return 0;
}
return this.image.height/this.scaleFactor;
}
this.pointIsInCard = function(mx, my){
if (mx >= this.x && mx <= (this.x + this.getWidth()) && my >= this.y && my <= (this.y + this.getHeight()))
{
return true;
}
else{
return false;
}
};
};
然後我有一個甲板類:
function Deck(x, y, w, h){
this.x = x;
this.y = y;
this.width = w;
this.height = h;
this.cards = [];
}
我需要在Deck
類類似於pointIsInCard
,而不是它會被稱爲pointIsInDeck
添加一個方法。邏輯將是相同的,即檢查傳入的點是否落入對象的邊界。所以看到代碼的重複,我想知道避免這種重複的良好設計實踐是什麼?我想到的一個選擇是提取方法,並創建一個通用對象的功能x
,y
,width
,height
,但再次從OOP原則,我認爲這種方法應該屬於類/對象。我感謝任何幫助!謝謝!
您通過哪裏畫線Helper類來搜索,點座標,w和h。 – Justinas
每個功能的參數是否相同? – guest271314
或者有方法的甲板和卡的超級/祖先。 – RobG