Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
67
rated 0 times [  69] [ 2]  / answers: 1 / hits: 30234  / 12 Years ago, fri, may 4, 2012, 12:00:00

I want to house a variable in a function. This variable will change state depending on user interaction. For example:


function plan_state(current){
if (current != ''){
state = current;
}
else {
return state;
}
}

When the document loads I call plan_state('me'), and when certain things happen I may call plan_state('loved'). The problem occurs when I run a function and want to check the current state:


alert(plan_state());

I get undefined back, but the value should be 'me' as I previously set this value on document load.


What am I doing wrong?


More From » function

 Answers
36

The function isn't stateful because the state variable is declared inside the function and therefore only exists for the lifetime of the function call. An easy solution would be to declare the variable globally, outside the function. This is bad bad bad bad.



A better approach is to use the module pattern. This is an essential pattern to learn if you're serious about javascript development. It enables state by means of internal (private variables) and exposes a number of methods or functions for changing or getting the state (like object oriented programming)



    var stateModule = (function () {
var state; // Private Variable

var pub = {};// public object - returned at end of module

pub.changeState = function (newstate) {
state = newstate;
};

pub.getState = function() {
return state;
}

return pub; // expose externally
}());


so stateModule.changeState(newstate); sets the state



and var theState = stateModule.getState(); gets the state


[#85793] Thursday, May 3, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
soniap

Total Points: 626
Total Questions: 119
Total Answers: 110

Location: Palestine
Member since Tue, Jul 20, 2021
3 Years ago
soniap questions
Mon, Jun 22, 20, 00:00, 4 Years ago
Fri, May 8, 20, 00:00, 4 Years ago
Fri, Mar 20, 20, 00:00, 4 Years ago
;