Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Square bracket notation and scope in JavaScript module pattern

I have been working with the module pattern in JavaScript and have a question about scope and square bracket notation (SBN).

Please consider the following simple example.

(function (module) {

    function myMethod(text) {
        console.log(text);
    }

    module.init = function (name) {

        // here I want to do something like 
        // eval(name)("hello");
        // using SBN, e.g.
        ..[name].call(this, "hello"); 
    };

})(window.Module = window.Module || {});

Module.init("myMethod");

From within the init function is it possible to call myMethod using SBN?

like image 633
Fraser Avatar asked Oct 03 '22 00:10

Fraser


1 Answers

You can put all of your methods into an object.

function myMethod(text) {
    console.log(text);
}

var methods = {myMethod: myMethod, ... };

module.init = function (name) {

    // here I want to do something like 
    // eval(name)("hello");
    // using square bracket notation.

    if(methods.hasOwnProperty(name)){
        methods[name].call(this, "hello"); 
    } 
    else {
        // some error that the method does not exist
    }
};
like image 176
qwertynl Avatar answered Oct 18 '22 02:10

qwertynl