Prometheus
Prometheus

Reputation: 33655

global variable in jquery

In jQuery is it possible to create a function that sets a variable which I can then access in another function. i.e. I need a global variable that can be accessed anywhere on the page.

Examples

$.fn.getRedemptionID = function(){
  var myVar = data.DATA[0].item1;
}

Upvotes: 0

Views: 212

Answers (4)

Apoorv Saxena
Apoorv Saxena

Reputation: 4236

A better way would be to use closure, to save your variable value in the following manner:

var application = (function(){
    var my_var;

    return {
        get_var: function(){
            return my_var;
        },
        set_var: function(value){
            my_var = value;
        }
    }
})();

application.set_var(34);
application.get_var;

It's better than using Global variables.

Upvotes: 0

KRyan
KRyan

Reputation: 7618

jQuery is still JavaScript, and can still be used like JavaScript. I.e. if you declare something outside of any block, it is global and can be accessed anywhere.

E.g.

var global = 42;
$(document).ready(function() {
    global = $('#something').val();
});

Upvotes: 0

jbabey
jbabey

Reputation: 46657

1) Global variables are bad.

2) Yes:

// explicit global (preferred)
$.fn.getRedemptionID = function(){
  window.myVar = data.DATA[0].item1;
}

// implicit global
$.fn.getRedemptionID = function(){
  myVar = data.DATA[0].item1;
}

Upvotes: 3

Fry_95
Fry_95

Reputation: 241

Just do this :

var myGlobalVar = null;

$.fn.getRedemptionID = function(){
  myGlobalVar = data.DATA[0].item1;
}

Then you can access myGlobalVar everywhere :)

Upvotes: 0

Related Questions