...

View Full Version : Javascript - Access a Global Variable from inside a function



PioStudios
05-18-2012, 08:52 PM
Hi,

Is is possible to access a global variable for use inside a function?

Thanks for help in advance

Mike

xelawho
05-18-2012, 09:30 PM
Mike,

you need to either:
a) post this question in a branch that is designated for questions (this one is for showcasing "finished" javascripts)
or
b) test it yourself

I recommend b as being the speedier and more satisfying course of action

felgall
05-18-2012, 10:21 PM
Well someone has moved the question to the right forum so it is only reasonable to answer it.

Three examples for you:


var a = 1;
b = function() {
var c = 2;
a = c;
}

In this example because the function b() has no local variable a the reference to that variable inside the function is taken to refer to the global variable.



var a = 1;
b = function() {
var a = 3, c = 2;
a = c;
}

In this version function b() does have its own ;ocal variable a and so the references within the function are to the local a and not to the global a. To reference the global variable we can change that code to:


var a = 1;
b = function() {
var a = 3, c = 2;
window.a = c;
}

The window.a reference is to the global variable a and not to the local variable a.

PioStudios
05-19-2012, 09:38 AM
Sorry for posting in the wrong forum. Genuine mistake.

@felgall - sincere thanks for your answer. It is excellent. Thanks for taking the time to explain it. Appreciate it.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum