Я практикую ООП в JavaScript в первый раз и не понимаю, почему наследование не работает.Игрок не наследует от CardHolder в JavaScript
Код:
function Card(s, v) {
if (arguments.length === 0) {
this.suit = SUITS[Math.floor(Math.random()*SUITS_LENGTH)];
this.val = VALS[Math.floor(Math.random()*VALS_LENGTH)];
}
else {
this.suit = s;
this.val = v;
}
}
Card.prototype = {
constructor: Card,
toString: function() {
return this.val + " of " + this.suit;
},
lowVal: function() {
if (this.val === "A") { return 1; }
else if (this.val === "J" || this.val === "Q" || this.val === "K") { return 10; }
else { return parseInt(this.val); }
},
highVal: function() {
if (this.val === "A") { return 11; }
else if (this.val === "J" || this.val === "Q" || this.val === "K") { return 10; }
else { return parseInt(this.val)}
}
};
function CardHolder() {
this.status = "in";
this.cards = [];
}
CardHolder.prototype = {
constructor: CardHolder,
deal: function() {
this.cards.push(new Card());
},
lowVal: function() {
var lowVal = 0;
for (var i = 0, len = this.cards.length; i < len; i++) {
lowVal += this.cards[i].lowVal();
}
return lowVal;
},
highVal: function() {
var highVal = 0;
for (var i = 0, len = this.cards.length; i < len; i++) {
highVal += this.cards[i].highVal();
}
return highVal;
},
score: function() {
if (this.highVal() > 21) { return this.lowVal(); }
else { return this.highVal(); }
}
};
function Player(id) {
CardHolder.call(this);
if (typeof(id)) {
this.id = id;
}
}
Player.prototype = Object.create(CardHolder.prototype);
Player.prototype = {
constructor: Player,
toString: function() {
var returnString = "Player " + this.id + ":\n";
for (var i = 0, len = this.cards.length; i < len; i++) {
returnString += this.cards[i].toString() + "\n"
}
return returnString;
}
}
Выход
var p = new Player();
p.deal();
console.log(p.toString());
Выходы Uncaught TypeError: undefined is not a function
. Что я думаю, означает, что p
не наследует функцию deal
от CardHolder
.
Почему это не работает?
Это имеет смысл и работает. Благодаря! –