Javier Brooklyn
Javier Brooklyn

Reputation: 634

Get a variable value outside from within a function defined by "var somthing ="

This is a function used in jQuery UI widgets and plugins -

var select = function( event, ui ) {
        var somevariable = 4;
    }

How can I get the value of var somevariable = outside this function?

Using it as a global variable doesn't work:

var somevariable;
var select = function( event, ui ) {
        var somevariable = 4;
    }

In this code var somevariable doesn't get the value '4' when it is placed before or after var select =

EDIT: To make it more detailed, I want to use this variable in another function like in the following jQuery UI plugin:

  $( "#id" ).autocomplete({
    minLength: 0,
    source: function( request, response ) {

        if (somevariable == 5)
        {
        //do something
        }

    },
    open: function( event, ui ) {

    somevariable = 5;

    }
});

In this case when the open: event is triggered, the value does not get retrieved by source:

Upvotes: 1

Views: 14770

Answers (1)

John Dvorak
John Dvorak

Reputation: 27277

Perhaps this is what you want?

var somevariable;
var select = function( event, ui ) {
    somevariable = 4;
}

By not having var on line 3, instead of being a new variable inside select, somevariable now refers to the variable declared on line 1.

If a variable is declared as a local variable inside a function, it cannot be accessed from outside the function (but it can be accessed from functions declared within that function, and its value can be passed around as usual). The fact that it cannot is, in fact, quite a powerful one, and it serves as a means of creating a private scope in Javascript.


Also, consider declaring your method via a function declaration:

var somevariable;
function select(event, ui) {
  somevariable = 4
};

(benefits: slightly shorter, hoisted to the top - you can call it above the place you define it; disadvantage: slightly less intuitive that it can be treated as a first-class citizen).

Upvotes: 6

Related Questions