我有完整的代码。我正在尝试调用AssignCard函数。我收到类型不匹配错误。我无法解决这个问题。这是我正在尝试的代码
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
var suits = new Array("\u2665", "\u2660", "\u2666", "\u2663");
var scale = new Array("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K");
ShuffledDeck = new Array();
DECK();
function person(name) {
self = this;
this.pName = name;
this.cardinHand = new Array();
function AssignCard(crd) {
this.cardinHand.push(crd);
return 1;
}
};
var p = new person("Roger");
crd = ShuffledDeck.pop();
p.AssignCard(crd);
crd = ShuffledDeck.pop();
p.AssignCard(crd);
console.log(p.Name);
console.log(p.cardinHand);
var p1 = person("Jiya");
crd = ShuffledDeck.pop();
p1.AssignCard(crd);
crd = ShuffledDeck.pop();
p1.AssignCard(crd);
console.log(p1.Name);
console.log(p1.cardinHand);
// console.log(po.Name);
function card(ste , scl) {
this.suite= ste;
this.scale= scl;
}
function DECK()
{
var num =0;
var ste;
var scl
var carddeck = new Array();
for (i = 0; i < 4; i++)
{
ste = suits[i];
for (j = 0; j < 13; j++)
{
carddeck[num] = {suite:ste, scl : scale[j]};
num = num + 1;
}
}
for(k=0;k<52;k++)
{
cardNUM = Math.floor(Math.random() * 52);
var crd = new card(carddeck[cardNUM].suite, carddeck[cardNUM].scl);
ShuffledDeck.push(crd);
}
}
</script>
</head>
<body>
</body>
</html>
我对如何创建多个实例感到困惑
答案 0 :(得分:2)
将您的函数更改为this.AssignCard = function()
,以便在实例上使用它,或者@Bergi注释,更好地使用Prototype(也是固定的命名约定):
function Person(name) {
self = this;
this.pName = name;
this.cardinHand = new Array();
}
Person.prototype.assignCard = function(crd) {
this.cardinHand.push(crd);
return 1;
}
快速测试:
var p = new Person("justin");
p.assignCard("spade");
console.log(p.cardinHand); //Logs ['spade']