Square bracket notation and scope in JavaScript module pattern

痴心易碎 提交于 2019-12-10 14:53:47

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/20888418/square-bracket-notation-and-scope-in-javascript-module-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!