5

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?

Fraser
  • 15,275
  • 8
  • 53
  • 104

2 Answers2

3

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
    }
};
qwertynl
  • 3,912
  • 1
  • 21
  • 43
  • Many thanks, this is what I ended up doing - it was really puzzling that I can simply call `myMethod()` but can't reference it via SBN... – Fraser Jan 02 '14 at 17:54
  • 1
    Yea. it is weird. but that is javascript for you :-D – qwertynl Jan 02 '14 at 17:55
1

As far as I know there is no way to do this without using eval.

That said, it is generally better to have a whitelist of allowed methods to be called, like so:

(function(module) {
    var methods = {
        "myMethod":function(text) {
            console.log(text);
        }
    };
    module.init = function(name) {
        methods[name].call(this,"hello");
    };
})(window.Module = window.Module || {});
Module.init("myMethod");

In this way, only methods that have been specifically defined in that "methods" object can be called.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Many thanks, this is actually what I have done - although it seems odd having to wrap the methods inside another object. To clarify, is it simply that there is no reference to the anonymous function hence no object in which to look for "myMethod"? – Fraser Jan 02 '14 at 17:51