0

I was wondering if it's possible to call a function by passing a string name. Following is the basic architecture:

Javascript:

"use strict";
function foo(){
   var f = this;
   f.fn = function(o){return fn(o)}

   function fn(o){
      o.name();
   }

   function a(){
      alert('a');
    }

    function b(){
      alert('bb');
    }

}

var f = new foo();


f.fn({name:'a'}); 
f.fn({name:'b'});

The code is setup at http://jsfiddle.net/rexonms/9c7bnkc9/.

rex
  • 985
  • 5
  • 28
  • 48

1 Answers1

0

You can achieve it using eval:

function foo(){
    var f = this;
    f.fn = function(o){return fn(o)}

    function fn(o){
        eval(o.name + '()');
    }

    function a(){
        alert('a');
    }

    function b(){
        alert('bb');
    }

}

var f = new foo();


f.fn({name:'a'});
f.fn({name:'b'});

Here is jsFiddle: http://jsfiddle.net/9c7bnkc9/2/

alexpods
  • 47,475
  • 10
  • 100
  • 94
  • You can use eval but you probably shouldn't. If your only solution is eval, you should probably consider changing some other part of your design to avoid eval. – James Montagne Jan 16 '15 at 19:10
  • @JamesMontagne In 99.9% cases you should not use `eval`, but you must know how it works, and what you can do with it. I have several cases in my career when using eval was necessary. And by the way, the was a question - and this is fully correct answer. (There is no answer with `eval` http://stackoverflow.com/questions/9464921/dynamically-call-local-function-in-javascript). – alexpods Jan 16 '15 at 19:19
  • @JamesMontagne Answer marked as accepted: "You cannot get a reference to a local variable by a string. You have to add the local objects to a namespace:" - FACEPALM (from here http://stackoverflow.com/questions/9464921/dynamically-call-local-function-in-javascript) – alexpods Jan 16 '15 at 19:24
  • I have not downvoted your answer because it is correct as eval is the only solution under the constraints laid out in the question. However, the opening line in that answer aside, I agree with the solution set forth in the remainder of the answer. I marked the questions as duplicate as I do believe the questions to be duplicates. However, there is currently no `eval` answer on that duplicate question. You can feel free to add your answer to that question as this one is now closed. I would suggest at least a small note on the fact that eval is dangerous, though that is entirely up to you. – James Montagne Jan 16 '15 at 19:33
  • In addition, if you feel my closing as duplicate was unjustified, you can vote to reopen (not sure what the rep threshold for that is). You may also downvote that answer and comment on the fact that the opening statement is false. – James Montagne Jan 16 '15 at 19:34
  • @JamesMontagne no, I think you duplicate mark was correct. – alexpods Jan 16 '15 at 19:38
  • @JamesMontagne I just was surprised when do not find `eval` answer in another thread. – alexpods Jan 16 '15 at 19:40