访问另一个函数中的局部变量

时间:2011-07-27 19:52:35

标签: javascript

这是我写的代码:

function p_deal(id) {
    var card1_val = Math.floor(Math.random() * deck.length);
    var card2_val = Math.floor(Math.random() * deck.length);
        var card1 = deck[card1_val];
        var card2 = deck[card2_val];
    var hand = card1 + ", " + card2;
var res = card1_val + card2_val;

document.getElementById(id).innerHTML = hand;

function hit(id) {
    if (bucket == 0) {
        bucket = " ";
    }

    var card3_val = Math.floor(Math.random() * deck.length);
    var nhand = deck[card3_val];
    bucket = bucket + " " + nhand + ", ";
    bucket_val = bucket_val + card1_val + card2_val + card3_val;

    if (bucket_val >= 22) {
        var r = confirm("Bust! By " + nhand);
        if (r == true) {
            refresh();
        }
        else {
            refresh();
        }
    }

    document.getElementById(id).innerHTML = bucket;

    light = light + 1;

    if (light == 5) {
        alert("Five Card Blackjack! You Win!");
        refresh();
    }
}

bucket val中的card_val变量来自p_deal(id)函数。为了让程序工作,每次调用两个函数时,card_val值必须是相同,但每次调用函数时都需要重新生成它们(因此多个玩家可以拥有不同的牌)。但是,作为局部变量,我发现很难在另一个函数中使用它们。我能在这做什么?

3 个答案:

答案 0 :(得分:1)

简单方法:将它们设为全局或在函数之间传递它们

更难但更明智的方法:改用对象并创建对象的变量属性。

答案 1 :(得分:1)

看起来你想要一个对象:

function Hand(id) {
    this.elem = document.getElementById(id);
    this.bucket = "";
    this.bucketVal = 0;
    this.deal = function() {
        this.card1 = Math.floor(Math.random() * deck.length);
        this.card2 = Math.floor(Math.random() * deck.length);
        this.elem.innerHTML = deck[this.card1] + ', ' + this.card2;
    }
    this.hit = function() {

        var newCard = Math.floor(Math.random() * deck.length);
        this.bucket += " " + deck[nhand] + ", ";
        this.bucketVal += this.card1 + this.card2 + newCard;

        if (this.bucketVal >= 22) {
            var r = confirm("Bust! By " + nhand);

            refresh();
        }

        this.elem.innerHTML = this.bucket;

        light = light + 1;

        if (light == 5) {
            alert("Five Card Blackjack! You Win!");
            refresh();
        }
    }
}

var player1Hand = new Hand('player1Id');
player1Hand.deal();
player1Hand.hit();

答案 2 :(得分:0)

使它们成为全局变量而不是局部变量。