It worked yesterday.
It worked yesterday.

Reputation: 4617

Accessing private methods of a JS Function

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

Upvotes: 1

Views: 44

Answers (2)

Danil Gaponov
Danil Gaponov

Reputation: 1441

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.

Upvotes: 0

dfsq
dfsq

Reputation: 193271

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

Upvotes: 3

Related Questions