On 7 Dec 2004 06:55:12 -0800, jeffg <je*********@fuse.net> wrote:
[snip]
I try to limit the scope of variables and avoid global variables.
Excellent! :D
[snip]
A function sets the value of a variable that is limited to the scope of
the function. Later, another function needs the variable but does not
need to call the first function and trigger everything else in that
function. What's the best practice way of getting at that variable
without making it global?
It may depend on your actual code. A URL would be nice. That said, the
general approach would be to have the two functions share the same
"private" scope. For example:
/* Global variables that will soon hold
* references to your functions.
*/
var myA, myB;
/* Define and call an anonymous function. When this occurs,
* a new scope will be created where you can place your
* common, local variables.
*/
(function() {
var myCommon;
/* These inner functions for a closure which keep the
* local variable, myCommon, in memory once the anonymous
* function returns.
*/
myA = function() {
/* ... */
};
myB = function() {
/* ... */
};
/* Note the call here... */
})();
Both of the functions, myA and myB, can now access myCommon. The pattern
is similar if myA and myB were methods of an object.
Take a look at <URL:http://www.crockford.com/#javascript> and
<URL:http://www.jibbering.com/faq/faq_notes/closures.html> for articles
that delve into this sort of thing more deeply.
Hope that helps,
Mike
--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.