Question

I have a UserInterface class with a public method that needs to be able to delegate its work to a private function based on a parameter. The name of the private wrapper needs to be called dynamically:

function UserInterface() {
  // ...

  this.getViewHtml = function(view) {  
    // Given this snippet, view would be passed in as 
    // either "First" or "Second".

    // Wrong syntax, I know, but illustrative of what
    // I'm trying to do, I think
    return 'get' + view + 'ViewHtml'();  
  };

  function getFirstViewHtml() {
    return someHtml;
  };

  function getSecondViewHtml() {
    return someHtml;
  };


  // ...
}

As you might expect, if I don't have the variable requirement, I can call the private function just fine.

How can I get my public function to access the appropriate private method using a variable-based function name? This is outside of any window object, so window['get' + view + 'ViewHtml'] doesn't work.

Any insight would be appreciated.

Was it helpful?

Solution

You need to define your private functions as methods of a private object:

function UserInterface() {    
  this.getViewHtml = function(view) {
    return methods['get' + view + 'ViewHtml']();  
  };

  var methods = {
    getFirstViewHtml : function() { return someHtml; },
    getSecondViewHtml : function() { return someHtml; },
  }
}

Alternatively you could use a switch:

this.getViewHtml = function(view) {
  switch(view) {
    case 'first': return getFirstViewHtml();
    case 'second': return getSecondViewHtml();
    default : throw new Error('Something is terribly wrong');
  }  
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top