billven
billven

Reputation: 11

Js variable definition

I've got a QML in Qt Creator 3.4.1, which every second updates the value of a JS function. Every time the function runs and then terminates. Now to the problem:

The first time the function is run I want to define a variable. This value is then changed by the function and shall be used the next time the code runs. I can only make a variable which redefines every time the code runs again

A simple example is this:

function func() {
  var input = 10

  input--

return input //input is now 9
}

Next time the code runs it shall use the new value of input, 9, instead of 10. How do I define this?

Upvotes: 0

Views: 45

Answers (4)

James J. Hill
James J. Hill

Reputation: 139

When you define a variable in a function, that variable is gone as soon as the function has completed execution. If you want to have a variable defined and used in the same function call each time, you will need to define the variable at least one level above the function definition.

Something you could do is define a function which returns a function which follows your requirements. For example,

var foo = (function(){
    var bar;
    return function() {
        if(bar === undefined){
            bar = 10; // First function call, define bar
        } else {
            bar--; // Every consecutive call, do something with bar
        }
    }
})();

When you first execute foo(), bar will be set to 10. Every consecutive call will decrement bar by 1.

Upvotes: 0

MichaelWClark
MichaelWClark

Reputation: 390

function func(input) {
return input--; //input is now input-1
}

before you were redeclaring input to =10 each run. input -1 =9. YOu need to do something like the above...or

function(i){
if(i.isNaN()){ i = 10; }

return i--;
}

Upvotes: 0

Jozef Mikušinec
Jozef Mikušinec

Reputation: 223

You need to declare the variable out of the function. Variables declared inside functions are only remembered while the function runs (closures being an exception).

var input = 10;

function func() {

  input--

return input //input is now 9
}

If you want the variable be undeclared before the function is first run, you can do:

var input;

function func() {
  if (input === undefined) {
    input = 10;
  }

  input--

return input //input is now 9
}

Upvotes: 0

geco17
geco17

Reputation: 5294

Try a global variable - it is deleted when the page is closed.

var input = 10;

function func() {
  input--;

  return input;
}

Upvotes: 2

Related Questions