Javascript: access function in close

I have a function name in a variable, but everything is inside a closure. With this variable I want to call a function, something like this

(function(func) { this[func]() ; // doesn't work function bar() {} function foo() {} })('bar') ; 

Maybe something like this or I should, for example, add functions to a variable, for example

 (function(func) { var ns = { bar: function() {}, foo: function() {} }; ns[func]() ; // OK })('bar') ; 
+7
source share
3 answers

Variables and functions declared in the current lexical field cannot be accessed by name using the [] syntax - only property keys (in your second example) can be dynamically searched based on the contents of another variable.

The only way around this is to resort to eval , which is almost never a good idea.

The exception applies to variables and functions declared in the global scope - in fact, these are window properties.

+9
source

Something like that:

 (new function() { this.a = function(x) { document.getElementById('out').innerHTML += x; } })['a']('boom.'); 

http://jsfiddle.net/CT4du/1/

Closing keeps everything personal. And usually, this in the closure only refers to window . But you can "publish" items in a "closure" without polluting the global space, first turning it into an anonymous object. This allows you to make one and only one method call on an object before it disappears ...

You can make ordinary objects, for example, use private, lexical variables and expose only those methods that you want to open.

 (new function() { var a = function(x) { document.getElementById('out').innerHTML += x; } var b = function() { a(d); } var c = function() { /* ... */ } var d = "whatever"; // expose two of them .. this.a = a; this.b = b; })['a']('boom.'); 
+1
source

In my experience, including a function inside a closure is one way to declare it "private" - such that nothing outside can access it. In addition, you should pay attention to the way to minimize the code:

Before:

 (function() { function privateFn(var1, var2) { //TODO } return { publicFn: function() { } } })(); 

After:

 (function() { function _a(_0, _1) { } return { publicFn: function() { } } })(); 

Note that privateFn no longer exists? minifier knows, by definition, that nothing can access this function outside — by name or otherwise. You seem to want one of your features to be publicly available.

+1
source

All Articles