简体   繁体   中英

Global Variable outside of function returning undefined

I have tried a bunch of different ways to avoid getting undefined from a global variable but it messes up the rest of the code. I am able to call the variable this.userHunger in all functions but a few. I know i must have gone wrong somewhere:

<html>
<head>
<script>
function user() 
{
    this.userHunger = 100;
    this.userHealth = 100;
    this.userFoodNumber = 10;

    this.checkForHungerHealthData = function() 
    {
        document.getElementById('userHealthDisplay').innerHTML = "Your Health:" + this.userHealth;
        document.getElementById('HungerBarVisual').innerHTML = "Your Hunger" + this.userHunger;
        document.getElementById('amountOfFood').innerHTML = "Amount of food" + this.userFoodNumber;
    }

    this.signInButton = function()
    {
        document.getElementById('myButtonSignIn').style.visibility="hidden";
        this.checkForHungerHealthData(); // displays current hunger and health
    }

    this.eatFood = function() 
    {
        if(this.userFoodNumber  > 0) 
        {
            this.userHealth = this.userHealth + 10;
            this.userHunger = this.userHunger + 50;
            this.userFoodNumber--;
            document.getElementById('amountOfFood').innerHTML = "Amount of food:" + this.userFoodNumber;
            document.getElementById('userHealthDisplay').innerHTML = "Your Health:" + this.userHealth;
            document.getElementById('HungerBarVisual').innerHTML = "Your Hunger is currently " + this.userHunger + "%";
        }
    }

    this.start=function()
    {
        this.hungerClockStart();
    }

    this.hungerClockStart=function()
    {
        this.setUserHungerClock(setInterval(this.updateHungerScreen,1000));
    }

    this.updateHungerScreen=function()
    {
        alert(this.userHunger); //Returns undefined
        if(this.userHunger >= 0) 
        {
            var subtractAmount=1;
            document.getElementById('HungerBarVisual').innerHTML = "Hunger is Currently at: " + this.userHunger + "%";
            this.userHunger--;
        }
    }
}

var user1 = new user();

</script>
</head>
<h1 id = "userHealthDisplay">Your Health:<br></h1>
<h1 id = "HungerBarVisual">Your Hunger:<br></h1>

<input id="myButtonSignIn" style="visibility:visible" type="button" value="Sign in" onclick="user1.signInButton(); user1.hungerClockStart()">

<body>
<h1 id = 'Notifyer1'><br></h1>
<h1 id = 'Notifyer2'><br></h1>
<h1 id = 'amountOfFood'>Amount of Food:</h1>
<input id="eatFoodButton" style="visibility:visible" type="button" value="Eat some food!" onclick="user1.eatFood()">

</body>
</html>

I keep getting an error inside the this.hungerScreenUpdate and cannot understand why.

this.setUserHungerClock(setInterval(this.updateHungerScreen,1000));

needs to be

this.setUserHungerClock(setInterval(this.updateHungerScreen.bind(this),1000));

In JavaScript, this is dynamic, not lexical, so this can change depending on how it's called. When you do setInterval(this.updateHungerScreen,1000) it doesn't call updateHungerScreen with the correct this value. You can use bind to bind a function to a specific context.


As the commenters have suggested, if you need it to work on IE8 and below, you need to either shim in bind or use Phrogz's technique of storing this as a variable.


Update

For an overview of how this works in JavaScript, see https://stackoverflow.com/a/13373383/1662998

Personally, I recommend shimming in bind for IE8 and below. That way you get to go ahead and use new features while maintaining backwards compatibility with older browsers. Just add this in a script at the top of your page, and you'll be good to go:

if (!Function.prototype.bind)
    Function.prototype.bind = function(context/*, ...preArgs */) {

        var f = this,
            preArgs = Array.prototype.slice.call(arguments, 1);

        if (typeof f != 'function')
            throw new TypeError('Function expected.');

        if (context != null)
            context = Object(context);

        return function bound(/* ...args */) {
            var args = Array.prototype.slice.call(arguments);
            return f.apply(context, preArgs.concat(args));
        };

    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM