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

3
  • possible duplicate of JavaScript property access: dot notation vs. brackets? Commented Jul 22, 2015 at 14:07
  • I guess only eval could do what you want without updating your code a bit. Commented Jul 22, 2015 at 14:09
  • 1
    @Kyll This is not what i have asked :) Commented Jul 22, 2015 at 14:11

2 Answers 2

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'}) );
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.