Grateful Grateful - 1 year ago 63
Javascript Question

Assigning functions to variables in javascript?

I used to have something like the following ...

var setFoo = function (value1) {
window.localStorage.setItem('foo1', value1);

var setFoo2 = function (value2) {
window.localStorage.setItem('foo2', value2);

.. however, I found that I was constantly doing ...

window.localStorage.setItem('something', value);

... so I decided to turn it into a function ...

function genericSetFoo(name, value) {
window.localStorage.setItem(name, value);

... and have the following instead ...

var setFoo = genericSetFoo('foo1', value1);
var setFoo2 = genericSetFoo('foo2', value2);

... however, now when I try to call
, the application complains of
. What am I doing wrong? I mean I could still do ...

var setFoo = function(value1) { genericSetFoo('foo1', value1) };
var setFoo2 = function(value2) { genericSetFoo('foo2', value2) };

... and it works too... but it defeats the whole point if I have to redefine the function in any case. So how do I tackle this?

Answer Source

What am I doing wrong?

You're calling window.localStorage.setItem() instead of returning a function that calls window.localStorage.setItem(). Remember, when you call a function and assign it to a variable you are assigning the return value of that function, not the function itself.

For example, when you do:

function a () { return 2 };

var two = a();

.. do you expect the variable two to be 2 or a function? Another example, if you do:

var x = document.getElementById('foo');

.. do you expect the variable x to contain a DOM element or a function?

So, you need to return a function instead of calling a function:

function genericSetFoo(name) {
    return function (value) {
        window.localStorage.setItem(name, value);

So now you can do:

var setFoo1 = genericSetFoo('foo1');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download