Reputation: 11
I have follwong code. I am trying call AssignCard function. I am getting Type Mismatch error. I am unable to fix this. Here is code i am trying
<!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>
I am confused about how to create a multiple instances
Upvotes: 1
Views: 50
Reputation: 104795
Change your function to this.AssignCard = function()
so you can use it on your instances, or as @Bergi commented, better to use Prototype (also fixed naming conventions):
function Person(name) {
self = this;
this.pName = name;
this.cardinHand = new Array();
}
Person.prototype.assignCard = function(crd) {
this.cardinHand.push(crd);
return 1;
}
A quick test:
var p = new Person("justin");
p.assignCard("spade");
console.log(p.cardinHand); //Logs ['spade']
Demo: http://jsfiddle.net/Z6RV3/2/
Upvotes: 2