Reputation: 23253
I'm trying to keep myself from having a very long code block inside an if
statement, so I'm trying to call another function into the current scope:
var f = function(){ alert(a); };
(function(){
var a = "abc.";
f(); //undefined
eval("("+f+")()"); //this works, but eval is evil
})();
I'm probably missing something very basic about scopes, or even other (better) ways to approach the whole thing, but I can't figure out whatever it is. Any ideas on how to do this? I don't want to pass in the variables I need through function arguments.
Thanks in advance!
Upvotes: 4
Views: 13529
Reputation: 14361
Surprised nobody said this. This is what I would do
function sayhi () {
alert("hi " + this.a);
}
(function () {
this.a = "foo";
sayhi.call(this);
}());
Upvotes: -1
Reputation: 150020
If you don't want to pass the required variables as parameters you need to make sure the function you are calling is at the same scope (or lower) than where those variables are defined.
So in your case if you bring the var f = ...
definition inside the immediately-executed function in parentheses it will be in the same scope as variable a
. I'm not sure how that fits with the if
statement that you mention but don't include in your code sample, but you can do something like this:
(function(){
var f = function(){ alert(a); };
// other code here if you have any
var a;
if ("your if condition" == "something") {
a = "abc.";
f();
}
})();
Or just declare a
in the same place you declare f
.
Upvotes: 1
Reputation: 26317
You need to make sure you are passing the variable that you want to alert to the function
var f = function(a){ alert(a); };
(function(){
var a = "abc.";
f(a); //passing it the reference to a
})();
Edit: Well if you really dont want to pass a variable. You need to first set a
in global scope. When using var
within a function, you are creating a variable that is local to that function. leave the var out and you are just updating the global version of it.
var f = function(){ alert(a); };
var a = ""; // declare a in global scope
(function(){
a = "abc."; // dont use var, we just update the global scope.
f(); // F runs and grabs a from global scope
})();
Upvotes: 1