3
function man(){

 function add(a,b){
     return a+b;
 }

 function sub(a,b){
     return a-b;
 }

 function pow(a){
     return a**a;
 }
}

man('pow',2);

Is there any way that I can call the power function using the call "man('pow',2)"..???

6 Answers6

2

No. This is one of the key ways to hide information/implementation in JS – inside a closure. There isn't any way to access a value that isn't exposed to the outside.

Perhaps you're looking for an object:

var man = {

 add(a,b) {
     return a+b;
 },

 sub(a,b) {
     return a-b;
 },

 pow(a) {
     return a**a;
 }
};

console.log(man.pow(2));
Community
  • 1
  • 1
qxz
  • 3,814
  • 1
  • 14
  • 29
2

If your functions would be in global scope, than just do

window[functionName](a, b);

But since they are in your private scope I suggest adding them to some array and than call it:

function man(func, arg1, arg2) {
    var functions = {
        add: function (a, b){
            return a+b;
        },
        sub: function(a, b){
            return a-b;
        },
        pow: function (a){
            return Math.pow(a, a);
        }
    };

    functions[func](arg1, arg2);
}

Note that ** works only in ES7

Justinas
  • 41,402
  • 5
  • 66
  • 96
1

If you store each function mapped to a key, you could then invoke the function by its key:

function man() {
  var funcs = {
    add: function(a, b) {
      return a + b;
    },
    sub: function(a, b) {
      return a - b;
    },
    pow: function(a) {
      return a ** a;
    }
  };
  return funcs[arguments[0]].apply(this, Array.prototype.slice.call(arguments, 1));
}

console.log('pow of 2 = ' + man('pow', 2));
console.log('add 2 and 6 = ' + man('add', 2, 6));
console.log('sub 2 from 8 = ' + man('sub', 8, 2));

apply allows you convert the arguments (which is like an array) into the equivalent of a bunch of parameters.

Array.prototype.slice.call allows you to convert the arguments into an actual array so that you can skip the first one (which was used to identify the function to call).

Community
  • 1
  • 1
Moishe Lipsker
  • 2,974
  • 2
  • 21
  • 29
1

You could use an object as reference to the functions.

function man() {
    function add(a, b) { return a + b; }
    function sub(a, b) { return a - b; }
    function pow(a) { return a ** a; }

    return { add, sub, pow }[arguments[0]](...[].slice.call(arguments, 1));
}

console.log(man('pow', 2));
console.log(man('add', 4, 5));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Well, not a good idea to use eval. But, this will work

function man(funName, a, b){

 function add(a,b){
     return a+b;
 }

 function sub(a,b){
     return a-b;
 }

 function pow(a){
     return a**a;
 }

 return (eval(funName))(a, b)
}

man('pow',2);
Sanchay Kumar
  • 566
  • 5
  • 11
0

You can use Javascript Closures in order to implement what you need here.

Nitesh Goyal
  • 586
  • 5
  • 11