开发者

Javascript: Calling a function written in an anonymous function from String with the function's names withoout eval?

Update2:

What I really wanted to ask was already argued in a different page. Please check the following entry.

(Thanks to BobS.)

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 'windo开发者_JAVA百科w', 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:

  1. Define functions that are only used in the closure.
  2. Avoid creating an Object in the closure that holds those functions in order to be accessed as obj['bar'].
  3. Avoid eval (if possible) in order to write code more simply in a straightforward manner (if exists).
  4. 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.


As Kobi wrote, eval might be a good option. Alternatively, is there any reason not to do

$(function(){
  var localNamespace = {};
  function bar() {
      alert("bar");
  }
  localNamespace['bar'] = bar;
  // Now bar() can be called by, well, localNamespace['bar']
}

Update: Similar SO entries, such as How can I access local scope dynamically in javascript?, seem to indicate you're out of luck without using one of these two approaches or something even uglier.


Inside your ready function:

window.bar = function bar() {
    // ...
}

Then, you can access window['bar'].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜