Update2:
What I really wanted to ask was already argued in a different page. Please check the following entry.
(Thanks to BobS.)
http://stackoverflow.com/questions/598878/how-can-i-access-local-scope-dynamically-in-javascript
Hello.
I've started using jQuery and am wondering how to call functions in an anonymous function dynamically from String. Let's say for instance, I have the following functions:
function foo() {
// Being in the global namespace,
// this function can be called with window['foo']()
alert("foo");
}
jQuery(document).ready(function(){
function bar() {
// How can this function be called
// by using a String of the function's name 'bar'??
alert("bar");
}
// I want to call the function bar here from String with the name 'bar'
}
I've been trying to figure out what could be the counterpart of 'window', which can call functions from the global namespace such as window["foo"]. In the small example above, how can I call the function bar from a String "bar"?
Thank you for your help.
Update:
Here's what I want:
- Define functions that are only used in the closure.
- Avoid creating an Object in the closure that holds those functions in order to be accessed as obj['bar'].
- Avoid eval (if possible) in order to write code more simply in a straightforward manner (if exists).
- Decide function's name dynamically via the URI parameter or anything variable.
Being a newbie of Javascript, I thought 'this' would be the counterpart of 'window' in the closure, and tried writing:
// in the closure
name = 'bar';
this[name]; // undefined ...
and failed (of course...).
All of these are for pursuit of further laziness. Javascript is kind of new to me and currently I've been trying to write code as lazy as possible.