Javascript: calling a function written by an anonymous function from String with function names withoout eval?

Update2:
What I really wanted to ask was already discussed on another page. Please check the following entry.
(Thanks to BobS .)
How do I access a local area dynamically in javascript?


Hello.

I started using jQuery and am wondering how to dynamically call functions in an anonymous function from String. Say, for example, 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 name 'bar'??
    alert("bar");
  }

  // I want to call the function bar here from String with the name 'bar' 
}

I tried to figure out what could be the analogue of a “window”, which can call functions from the global namespace, for example window [“foo”]. In the small example above, how can I call the function panel from the string "String"?

.

:
:

  • , .
  • , obj ['bar'].
  • eval ( ), ( ).
  • URI .

Javascript, , 'this' "" :

// in the closure
name = 'bar';
this[name]; // undefined ...

(...).
. Javascript , .

+3
2

, eval . , -

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

Update: SO, javascript?, , , , - .

+2

ready:

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

window['bar'].

+2

Source: https://habr.com/ru/post/1735867/