2017-01-23 45 views
1

我想要訪問該對象的字符串,並傳遞給函數,但不知道如何。 分裂這裏不允許使用:訪問傳遞到原型函數的值

var Result = { "win": 1, "loss": 2, "tie": 3 } 

function PokerHand(hand) { 
} 
PokerHand.prototype.compareWith = function(hand){ 
    // Start your coding here... 
    var myHand = this.hand.split(' '); 
    var opHand = hand.split(' '); 
    if (myHand[0] > opHand[0]) 
     return Result.win; 
    if (this.hand != hand) 
     return Result.win; 
    return Result.tie; 
} 
var player = "4S 5H 6H TS AC"; 
var opponent = "3S 5H 6H TS AC"; 
var p = new PokerHand(player); 
var o = new PokerHand(opponent); 
p.compareWith(o) 

回答

1

試試這個。有用。 compareWith()函數中的參數應該是一個PokerHand,而不是一個手。所以,我只是在使用手牌的地方做了手球。

還有一件事,PokerHand的構造函數需要有一個屬性。

var Result = { "win": 1, "loss": 2, "tie": 3 } 
 

 
function PokerHand(hand) { 
 
    this.hand = hand; 
 
} 
 
PokerHand.prototype.compareWith = function(pokerHand){ 
 
    // Start your coding here... 
 
    var myHand = this.hand.split(' '); 
 
    var opHand = pokerHand.hand.split(' '); 
 
    if (myHand[0] > opHand[0]) 
 
     return Result.win; 
 
    if (this.hand != pokerHand.hand) 
 
     return Result.win; 
 
    return Result.tie; 
 
} 
 
var player = "4S 5H 6H TS AC"; 
 
var opponent = "3S 5H 6H TS AC"; 
 
var p = new PokerHand(player); 
 
var o = new PokerHand(opponent); 
 
console.log(p.compareWith(o))

+0

我仍然得到'類型錯誤:你爲什麼需要這行不能讀取屬性的undefined' – JohnnyBizzle

+0

'分裂'? 'this.hand = hand;' – JohnnyBizzle

+1

它是因爲一個Object.constructor必須有一個Object.property來存儲對象數據。因此,當您調用PokerHand構造函數並傳遞一手牌時,它必須在PokerHand對象實例上設置。 'this'是指構造函數中的Object。從而。 this.hand = hand基本上將手放在特定的PokerHand Object實例上。 – Piyush