Jump to content

How can I create a global variable from inside one function for another function to use?


phpjayx

Recommended Posts

function parseDataJson2(returnValue) //NEW REQ 3

{

var listData2 = $.parseJSON(returnValue);

var cellHtml = '';

for (var i = 0; i < listData2.length; i++)

{

var dataItem2 = listData2;

 

 

 

}

}

 

I have the variable dataItem2 that I would like to be accessable from another function outside of this one. How do I make this a global variable?

 

Or if there is an alternate way to get the data, that would be great too..

 

 

Thanks in advance

Link to comment
Share on other sites

/*
* Method 1: Declare the variable outside of the function.
*/

var myVar;

function myFunc()
{
   myVar = "This is a string";
}

alert(myVar);

 

/*
* Method 2: Return data from the function.
*/

function myFunc()
{
    return "This is a string";
}

var myVar = myFunc();
alert(myVar); // You could also: alert(myFunc());

Edited by Xaotique
Link to comment
Share on other sites

  • 4 months later...

While I agree that global functions should not have side effects, ever, "global" is key in this advice. After all, in JavaScript functions are objects, and a constructor or member functions manipulate the state of the object. OO is about state and your can't change state without side effects.

 

Bit of a detour but an important distinction IMO. Side effects good, ignoring encapsulation bad. To put it simply.

Link to comment
Share on other sites

Uhuh, but you didn't reference any of that. Maybe it should've been obvious but I prefer being explicit. In any case let's leave it at this, we're going way off topic. Cool?

Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.