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)"..???

0

6 Answers 6

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));

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

How about environments where we don't have window object - e.g NodeJS?
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));

Comments

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);

Comments

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).

Comments

0

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

1 Comment

And how to use these Closures in this situation?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.