简体   繁体   English

JavaScript模块模式中的方括号符号和范围

[英]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). 我一直在使用JavaScript中的模块模式,并且对范围和方括号表示法(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? init函数中可以使用SBN调用myMethod吗?

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

As far as I know there is no way to do this without using eval . 据我所知,没有使用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. 这样, 只能调用在该“方法”对象中专门定义的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM