javaScript Global Variables
I’ve found interesting tip yesterday while programming using javascript about global variables. My Problems start when i’m trying to access variabel that placed on function. Variabel in a fuction defined using “var” keyword is only available in current function only (local), when the function finished doing his job, it’s gone… you can’t access it in another function.
My problem start at variable scope :
function showVar1 () {
var localVar1 = 'helo, i am from local 1'; // local variable
alert(localVar1); // helo, i am from local 1
}
function showVar2 () {
var localVar2 = 'helo, i am from local 2'; // local variable
alert(localVar2); // helo, i am from local 2
alert(lovalvar1); // undefined ! ; it make me stress
}
// now test :
showVar1();
alert(localvar1); // undefined !
showVar2();
The case & Solution :
Now, i want make a variable created in function but it can be access from anonther function, the ansfer ? corect ! the Global Varibles. We must first create a variable defined outside the function.
I found on the net thus global variabels can accessed via window object, it’s correct but in Internet Explorer? you’ve make mistake !, it’s only can be adopted in Netscape family browsers (Firefox, Mozzila, etc..). So, the solution is using object in a javacript, yup, simple class. The above code revised like this :
function dataStorage() { // class constructor
var var1;
var var2;
}
var myData = new dataStorage();
function showVar1 () {
var localVar1 = 'helo, i am from local 1'; // local variable
alert(localVar1); // helo, i am from local 1
myData.var1 = localVar1; // save in global object variable
}
function showVar2 () {
var localVar2 = 'helo, i am from local 2'; // local variable
alert(localVar2); // helo, i am from local 2
alert(myData.var1); // helo, i am from local 1
}
// now test :
showVar1();
alert(myData.var1); // helo, i am from local 1
showVar2();
I’ve use this technique in http://www.melayuonline.com photo gallery sidebar , it’s very usefull. Found usefull or any comments ?
Oh, eh, is there a typo ? sory for that, i’am not good in english ![]()
Thank you so much! People like you that post their knowledge are freak’in awesome!