dynamically call local function in javascript

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 and public:

var public  = {},
    private = {};

public.publicMethod = function(number, otherarg) {
  // `.apply` with a fixed array can be replaced with `.call`
  private['privateMethod' + number].call(this, otherarg);
};

private.privateMethod1 = function(arg) {
  //do something with arg
};

private.privateMethod2 = function(arg) {
  //do something else with arg
};

return public; // expose public, but not private

Leave a Comment