gpt4 book ai didi

javascript - Player 不会从 JavaScript 中的 CardHolder 继承

转载 作者:行者123 更新时间:2023-11-30 17:21:54 24 4
gpt4 key购买 nike

我是第一次在 JavaScript 中练习 OOP,不明白为什么继承不起作用。

代码:

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 没有从 CardHolder 继承 deal 函数。

为什么它不起作用?

最佳答案

问题是

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;
}
}

正在覆盖在

中分配给 Player.prototype 的值
Player.prototype = Object.create(CardHolder.prototype);

为避免这种情况,您可以这样做:

Player.prototype = Object.create(CardHolder.prototype);

Player.prototype.constructor = Player;

Player.prototype.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;
};

关于javascript - Player 不会从 JavaScript 中的 CardHolder 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25008006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com