开发者

Best practice: Javascript/Jquery saving variable for later use

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(){

...

开发者_如何学Go 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!


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜