2017-02-06 28 views
0

我有一個卡類:最佳設計實踐分開常見的代碼?

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原則,我認爲這種方法應該屬於類/對象。我感謝任何幫助!謝謝!

+0

您通過哪裏畫線Helper類來搜索,點座標,w和h。 – Justinas

+0

每個功能的參數是否相同? – guest271314

+0

或者有方法的甲板和卡的超級/祖先。 – RobG

回答

3

你在做什麼的常用方法是附加一個Rectangle或類似的實例與功能到這兩個目標,即:

​​

然後,只需將它添加到CardDeck

function Card() { 
    this.rect = new Rectangle(/* Your card shape */); 

    // ... 
} 

function Deck() { 
    this.rect = new Rectangle(/* Your deck shape */); 

    // ... 
} 

你可以這樣做:

card.rect.containsPoint(); 
deck.rect.containsPoint(); 
+0

好的,我喜歡這種方法。我喜歡繼承的組合。我想我會採用這種方法。 – kofhearts

+0

也許不是這個。我可以將它命名爲我認爲更具描述性的邊界。你怎麼看? – kofhearts

+0

@ user734861當然,無論適合你的應用程序。 – Marty

1

如果這些是與繪圖相關的類,它們都會從Rectangle之類的東西繼承,它們都會從中繼承此行爲。

如果它們是遊戲相關的,我寧願他們各自引用Rectangle(或它的子類),他們將委派所有UI相關的任務;然後將其減少到上一段的解決方案。

0

可以使用Function.prototype.call()設置this在函數調用

function Card() { 
    this.x = 1; this.y = 2; 
}; 

function Deck() { 
    this.x = 10; this.y = 20; 
} 

function points(x, y) { 
    // do stuff 
    console.log(x, this.x, y, this.y); // `this`: `c` or `d` 
} 

var c = new Card(); 

var d = new Deck(); 

points.call(c, 3, 4); // `this`: `c` within `points` call 

points.call(d, 100, 200); // `this`: `d` within `points` call