0

I'm struggling to call a Javascript function dynamically in my code.

const MyObject = (function() { 

    function _myPrivateFunction() {
        console.log('_myPrivateFunction()');
    }

    const _MyObject = function() {
        console.log('_MyObject');
    };

    _MyObject.prototype = { 

        myPublicFunction: function() {
            _myPrivateFunction(); // Ok

            let functionName = '_myPrivateFunction';
            window[functionName]();   // Uncaught TypeError: window.functionName is not a function
            window["functionName"](); // Same error.
        }
    };

    return {
        init: _MyObject
    }   

})();

let obj = new MyObject.init();
obj.myPublicFunction();

Can someone show me the correct way to achieve this ?

Duddy67
  • 836
  • 2
  • 10
  • 26
  • 1
    `_myPrivateFunction` is declared within the scope of your function, so it's not available on the global `window` object. If you need to do this then you should store your function in an object `const fns = {_myPrivateFunction: function() {...}}`, then use that to call your function `fns[functionName]()`, make sure to forward any arguments and the `this` binding to it if you want those retained within `_myPrivateFunction` – Nick Parsons Oct 01 '22 at 12:35
  • It's private, not a property of `window`. Why do you want to call it "dynamically"? Why not just `if (functionName == '_myPrivateFunction') _myPrivateFunction();`? – Bergi Oct 01 '22 at 13:16
  • `return { init: _MyObject }` - don't do that. It makes no sense to have an `init` method be the constructor. Just make `MyObject` itself the constructor function so that you can call `new MyObject()`. – Bergi Oct 01 '22 at 13:17

0 Answers0