1

我有以下代码。我正在尝试调用 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>

我对如何创建多个实例感到困惑

4

1 回答 1

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']

演示:http: //jsfiddle.net/Z6RV3/2/

于 2013-09-11T14:33:48.957 回答