Convert JavaScript local scope variable to global or pass?
Moderator: General Moderators
- JAB Creations
- DevNet Resident
- Posts: 2341
- Joined: Thu Jan 13, 2005 6:44 pm
- Location: Sarasota Florida
- Contact:
Convert JavaScript local scope variable to global or pass?
Can a local scope JavaScript variable be converted to a global scope? If not how can we pass it's value to a variable not defined in a function?
Re: Convert JavaScript local scope variable to global or pass?
For javascript running in browser "global" scope would be window:
Code: Select all
(function() {
var q = "sdf";
window.q = q;
})();
(function() {
console.log(q);
})();
- JAB Creations
- DevNet Resident
- Posts: 2341
- Joined: Thu Jan 13, 2005 6:44 pm
- Location: Sarasota Florida
- Contact:
Re: Convert JavaScript local scope variable to global or pass?
I keep getting console not defined errors. I haven't had any success in logging anything to the console...other then errors.
Suggestions please?
Re: Convert JavaScript local scope variable to global or pass?
console.log is a function that comes with firebug.JAB Creations wrote:I keep getting console not defined errors. I haven't had any success in logging anything to the console...other then errors.Suggestions please?
Highly recommended when playing around with javascript/css.
- Kieran Huggins
- DevNet Master
- Posts: 3635
- Joined: Wed Dec 06, 2006 4:14 pm
- Location: Toronto, Canada
- Contact:
Re: Convert JavaScript local scope variable to global or pass?
Attaching a variable to a DOM node (like window) makes it available globally. I often use that method for setting timers and such (so they can be overridden / overwritten by other function calls) - a handy trick.http://javascript.crockford.com/survey.html wrote:Named variables are defined with the var statement. When used inside of a function, var defines variables with function-scope. The vars are not accessible from outside of the function. There is no other granularity of scope in JavaScript. In particular, there is no block-scope.
Any variables used in a function which are not explicitly defined as var are assumed to belong to an outer scope, possibly to the Global Object.
Vars which are not explicitly initialized are given the value undefined.
Vars are not typed. A var can contain a reference to an object, or a string or a number or a boolean or null or undefined.
A new set of vars is made every time the function is called. This allows functions to be recursive.
- JAB Creations
- DevNet Resident
- Posts: 2341
- Joined: Thu Jan 13, 2005 6:44 pm
- Location: Sarasota Florida
- Contact:
Re: Convert JavaScript local scope variable to global or pass?
I found a way around the issue, thanks for the clarifications.