Kyrbi
Kyrbi

Reputation: 2250

Can't update all variables from function

this is my JS:

var money = 4;
var thirst = 50;
function satisfy(what,how,price,sBar){
    if(price<=money){
        what=what+how;
        money=money-price;
        updateBar(sBar,what);
        updateMoney();
    } else {
        log.unshift("D"+day+" "+hour+":"+minute+" - Poor hobo, you don't have enough money for that. <br>");
        updateLog();
    };
};

And this is in my html

<a onClick="satisfy(thirst,30,0.84,'#thirst')";>buy</a>

After I click it problem is that global variable for thirst doesn't get updated but money global variable does get updated. How can I fix it to make thirst global variable updated too?

Thank you, very much.

Upvotes: 1

Views: 56

Answers (3)

jrode
jrode

Reputation: 411

If you absolutely had to "pass by reference" you could pass an object then modify the contents inside the function.

var money = 4,
    thirst = 50,
    myObj = {
      what: 'thirst',
      how: 30,
      price: 0.84,
      sBar: '#thirst'
    }

function doSomething(obj) {
   obj.what = 'hunger';
   obj.how = 20;
}

doSomething(myObj);
console.log(myObj.what); // "hunger"

Upvotes: 1

Kevin Ji
Kevin Ji

Reputation: 10489

This is because JavaScript numbers are passed by value, not by reference, meaning that a copy of thirst is created and modified. Why not return a value instead:

HTML:

<a id="buy-link">buy</a>

JavaScript:

var money = 4;
var thirst = 50;

function satisfy(what, how, price, sBar) {
    if (price <= money){
        what += how;
        money -= price;
        updateBar(sBar,what);
        updateMoney();
    } else {
        log.unshift("D" + day + " " + hour + ":" + minute + " - Poor hobo, you don't have enough money for that. <br>");
        updateLog();
    }

    return what;
}

var buyLink = document.getElementById("buy-link");
buyLink.addEventListener("click", function() {
    thirst = satisfy(thirst, 30, 0.84, '#thirst')
}, false);

I also removed some of your unneeded semicolons, converted your event handler into using the standard addEventListener function, and cleaned up your code a bit.

Upvotes: 1

AwokeKnowing
AwokeKnowing

Reputation: 8206

add

thirst=what;

after:

updateMoney();

however, since you're using it as a parameter, I suspect you're planning to pass different variables besides "thirst" to the function

in that case, just pass a string, like "thirst". then in your function have something like

if (what=="thirst")
      thirst=what;
if (what=="hunger")
      hunger= what;

etc

Upvotes: 0

Related Questions