Reputation: 13
I've hunted around for about an hour or so trying to glean whatever I could about variable scope in jscript/jquery and by all accounts, my code should work. Right now I just want to be able to read a global variable from a function. My code isn't working and right now it's very basic. Eventually I will need to manipulate the global variable, but one step at a time here:
var fooBar;
fooBar = "blah";
$('.var').click(function (fooBar) {
alert(fooBar);
});
HTML:
<span class="var">(Button Test)</span>
It returns [Object object] in the alert box. I was really hoping it would return Blah for me. I know this is a very very basic question, but all examples I'm finding are pretty complex and it's pretty difficult for me to boil it down to the very basic part that I need. Any help is greatly appreciated.
Upvotes: 1
Views: 540
Reputation: 22297
Global variables in Javascript are actually members of window
, if you have a scoping conflict with a local variable, like your fooBar
parameter, then you can fully qualify your global fooBar
variable like so:
var fooBar;
fooBar = "blah";
$('.var').click(function (fooBar) {
alert(window.fooBar);
});
In fact, I make it a point to always fully qualify global variables with window
so as to avoid any confusion or conflicts. Indeed, I would write the whole thing like this:
window.fooBar = "blah";
$('.var').click(function (fooBar) {
alert(window.fooBar);
});
Upvotes: 1
Reputation: 13709
You don't need fooBar
in the parameters for your function. This will suffice:
var fooBar;
fooBar = "blah";
$('.var').click(function() {
alert(fooBar);
});
You've got too much code, is all :)
Upvotes: 0
Reputation: 3502
Remove the fooBar from the function as it is making a local scope variable which will be being used rather than your global.
$('.var').click(function () {
alert(fooBar);
});
Upvotes: 2
Reputation: 630369
You need to remove it as a parameter, like this:
var fooBar;
fooBar = "blah";
$('.var').click(function () {
alert(fooBar);
});
The reason you see [Object object]
is that the first parameter passed to the function (and any other event handler in jQuery) is the jQuery event
object, and that parameter being named the same means that inside your function fooBar
refers to it, because it's more local. Your variable is available inside, it's just getting overridden by a more local version currently because of the same name being used...remove it like I have above and you'll be all set.
Upvotes: 5