1

I have following javascript code

function MyFunc () {

    var add = function () {
        return "Hello from add";
    };

    var div = function () {
         return "Hello from div";
    };

    var funcCall =  function (obj) {

        if (!obj) {
            throw new Error("no Objects are passed");
        }
      return obj.fName();


    };

  return {
    func: function (obj) {
      funcCall(obj);
    }
  };

}

var lol = new MyFunc();

When lol.func({fName: add}); is passed it should invoke the function private function add or when lol.func({fName: div}); is passed it should invoke the private div function. What i have tried does not work. How can i achieve this.

DEMO

It worked yesterday.
  • 4,507
  • 11
  • 46
  • 81

2 Answers2

3

In this case it's better to store your inner function in the object so you can easily access this with variable name. So if you define a function "map"

var methods = {
    add: add,
    div: div
};

you will be able to call it with methods[obj.fName]();.

Full code:

function MyFunc() {

    var add = function () {
        return "Hello from add";
    };

    var div = function () {
        return "Hello from div";
    };

    var methods = {
        add: add,
        div: div
    };

    var funcCall = function (obj) {

        if (!obj) {
            throw new Error("no Objects are passed");
        }

        return methods[obj.fName]();
    };

    return {
        func: function (obj) {
            return funcCall(obj);
        }
    };

}

var lol = new MyFunc();
console.log( lol.func({fName: 'add'}) );
dfsq
  • 191,768
  • 25
  • 236
  • 258
0

When you pass lol.func({fName: add}) add is resolved in the scope of evaluating this code, not in the scope of MyFunc. You have to either define it in that scope like:

function MyFunc () {

    var add = function () {
        return "Hello from add";
    };

    var div = function () {
         return "Hello from div";
    };

    var funcCall =  function (obj) {

        if (!obj) {
            throw new Error("no Objects are passed");
        }
      return obj.fName();


    };

  return {
    add: add,
    div: div,
    func: function (obj) {
      funcCall(obj);
    }
  };

}
var lol = new MyFunc();
lol.func({fName: lol.add});

Or use eval.

Danil Gaponov
  • 1,413
  • 13
  • 23