there are plenty of similar questions out there about calling functions by name dynamically. However, I can't find a solution to my specific problem where I have local functions inside a closure without exposing the functions to the public interface of my object.
Lets see some code (this is a fictional example)...
(function(window,$) {
MyObject = (function($) {
var obj = {};
obj.publicMethod = function(number,otherarg) {
this['privateMethod'+number].apply(this,[otherarg]);
};
var privateMethod1 = function(arg) {
//do something with arg
};
var privateMethod2 = function(arg) {
//do something else with arg
};
return obj;
})($);
window.MyObject = MyObject;
})(window,jQuery);
This doesn't work because "this" is MyObject and the local functions are not exposed. Also I'd like to be able to check if the function exists before trying to call it. eg.
var func_name = 'privateMethod'+number;
if($.isFunction(this[func_name])) {
this[func_name].apply(this,[otherarg]);
}
I'm not really sure how to proceed, short of exposing my private functions to the public interface, it all works then.
obj.privateMethod1 = function(arg) {
//do something with arg
};
obj.privateMethod2 = function(arg) {
//do something else with arg
};
I'm running out of ideas. Your help and advise is greatly appreciated.
The fact that you cannot call these functions from outside of the scope within which they are defined is a fundamental part of javascript, and indeed, all programming languages.
The only way to call these functions is to make them public. A convention based approach can be applied instead however. The underscore prefix is fairly ubiquitous and generally understood to mean "not intended to be called as a public function" eg:
The private functions are local variables and not part of any object. So, the
[...]
notation for accessing a property is never going to work since there is no object the private functions are properties of.Instead, you could make two objects:
private
andpublic
:You cannot get a reference to a local variable by a string. You have to add the local objects to a namespace:
Assuming you only have a couple of functions to call, you can create your own version of Window to use to call the functions:
Then in your code:
Just make sure the functions are defined when you add them to the object. In a module where the functions don't exist at load time, you can add them when the module is initialized:
I'm surprised that incorrect answer is marked as accepted. Actually you CAN get a reference to a local variable by a string. Just by using
eval
:Actually this code is very bad and in 99.9% cases you should not use
eval
. But you must know how it works and what you can do with it. I myself had a few very specific cases when usage ofeval
was necessary.