Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Creating a function with state

Tags:

javascript

I want to build a javascript function that maintains state. Here's a pattern that I've come up with, but something in the back of my mind tells me this is an anti-pattern.

function f() { 
    var state = 1;
    f = function() {
        return state++;
    };
    return f();
};

Is there anything wrong with this? If so, what's a better approach?

like image 974
JnBrymn Avatar asked Nov 17 '11 03:11

JnBrymn


People also ask

What is JavaScript state function?

State describes the status of the entire program or an individual object. It could be text, a number, a boolean, or another data type. It's a common tool for coordinating code. For example, once you update state, a bunch of different functions can instantly react to that change.

What are the 3 ways we can define a function in JavaScript?

There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.


1 Answers

Well it's a matter of opinion what the best way is, but (although I know it works) I'm a little uncomfortable with having the function overwrite itself. A similar pattern that doesn't do that but still uses practically the same closure idea is this:

var f = function() {
           var state = 1;
           return function() {
              return state++;
           };
        }();

Or here is another way:

function f() {
   return f.state++;
}
f.state = 1;

Of course with the f.state method the advantage and disadvantage (depending on your needs) is that the .state property can be read and modified by other code.

like image 98
nnnnnn Avatar answered Oct 22 '22 02:10

nnnnnn