Gergő Sz.
Gergő Sz.

Reputation: 11

Javascript: parameter function

How can I save "back" a variable in a JS parameter function like this:

var warehouseCapacity = 100;
var wood = 0,
    wood_production = 1;

function onLoad() {
    setInterval(outCalc(), 1000);
}

function outCalc() {
    calc(wood, wood_production, "wood_paragraph");
}


function calc(materialVar, productionVar, Id) {
    if (materialVar < warehouseCapacity) {
        if ((warehouseCapacity - materialVar) < productionVar) {
            document.getElementById(Id).innerHTML = warehouseCapacity;
        } 
        else {
            materialVar += productionVar;
            document.getElementById(Id).innerHTML = materialVar;
        }
    }
    else{
        //The warehouse is full so it can't hold any more materials.
    }
}

It only writes out ones because it doesn't set back the imported "materialVar". It imports in the value of the "materialVar". If I have written this without parameters it would work perfectly.

Ask if anything is not clear please.

Sorry for my mistakes, but I am not a native speaker.

Upvotes: 0

Views: 48

Answers (2)

Derek Peterson
Derek Peterson

Reputation: 603

Your change to materialVar in the first else block of calc doesn't update the variable passed in as a parameter because it is a type that is passed by value. That means that the function gets the value of the variable, but not a reference to the variable. To continue using parameters rather than a global variable (which is a good thing), you can return materialVar from calc:

function calc (materialVar, productionVar, Id) {
  // ...
  return materialVar;
}

Then, in outCalc, you can make the call look like this:

wood = calc(wood, wood_production, "wood_paragraph");

That will update the wood variable each time outCalc is called.

One last thing: your setInterval has a little bug. It calls outCalc immediately, rather than waiting for the timeout, and it only calls it once.

Upvotes: 1

Chet
Chet

Reputation: 3729

What you are referring to is "pass by reference" which isn't available for primitive types in JavaScript. Either change materialVar to an object which holds a number field, or return materialVar.

Example:

var warehouseCapacity = 100;
var wood = { amount: 0 };
var wood_production = 1;

function onLoad() {
    setInterval(outCalc(), 1000);
}

function outCalc() {
    calc(wood, wood_production, "wood_paragraph");
}

function calc(materialVar, productionVar, Id) {
    if (materialVar.amount < warehouseCapacity) {
        if ((warehouseCapacity - materialVar.amount) < productionVar) {
            document.getElementById(Id).innerHTML = warehouseCapacity;
        } else {
            materialVar.amount += productionVar;
            document.getElementById(Id).innerHTML = materialVar.amount;
        }
    } else {
        //The warehouse is full so it can't hold any more materials.
    }
}

Upvotes: 1

Related Questions