views:

54

answers:

3

Hello there,

I'm sure, this question has been answered somewhere before but I just couldn't find it.

If within a function a variable has been defined, what is the best practice to save it for later use? 1. Saving it "globally"?
foo = 'bar';
...
function bar(){
...
foo = 'bat';
return foo;
}
...

Here, the variable will be altered later on. 2. Or saving it within a hidden form field within the HTML-DOM?

`Thanxs!

+1  A: 

Saving it as a global JavaScript variable is by far the most efficient.

EDIT: If the data you want to save is associated with an element on the page (for example, each row in a table has a bit of data associated with it), and you are using jQuery, there is a data() method which is more efficient than setting an attribute on the element or something similar.

BudgieInWA
+2  A: 

It depends on the context, but probably: In a variable defined at the top level of a closure that wraps the set of functions to which it applies.

i.e.

var exports = function () {
    var stored_data;
    function set_data(foo) {
        stored_data = foo;
    }
    function get_data() {
        return stored_data;
    }
    return { get: get_data, set: set_data };
}();

This avoids the risk of other scripts (or other parts of your own, potentially very large, script) overwriting it by accident.

David Dorward
+1  A: 

The HTML5 spec has defined a solution to this question: If you are using HTML5, you can specify data attributes in your DOM.

See this page for more info: http://ejohn.org/blog/html-5-data-attributes/

This is now the standardised way of doing it, so I guess that it's considered best practice. Also John Resig, who wrote the blog I linked to above, is the author of JQuery, so if it's good enough for him, who am I to argue.

The really good news is that you don't even have to be using an HTML5-compatible browser for this technique to work - it already works in older browsers; it's just that now it's been encoded into the standard, and there's a defined way to do it.

That said, there's nothing wrong with a global variable in your Javascript as long as you avoid polluting the namespace too much, and it would be more efficient from a performance perspective, so there's plenty of merit in that approach as well.

Spudley
Hi Spudley, thanks for your answer. I just tried Resig's way. However using attributes like "data-name" is presently invalid Code (W3C) when using XHTML 1.0 Strict :-(
Mike
@Mike: John Resig's blog does discuss briefly how to do it in XHTML (additional namespace), and links to another blog that discusses it in more detail. However, I would suggest moving away from XHTML strict anyway now. XHTML has had its day; HTML5 is a far more powerful spec, and you'll lose functionality going forward if you don't make the jump sooner or later (and at this stage, it's just a change to your doctype, so it's an easy jump to make).
Spudley