JavaScript模块模式中的方括号表示法和范围 [英] Square bracket notation and scope in JavaScript module pattern

查看:126
本文介绍了JavaScript模块模式中的方括号表示法和范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用JavaScript中的模块模式,并对范围和方括号表示法(SBN)有疑问。

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

请考虑以下简单示例。

(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");

init 函数中可以实现使用SBN调用 myMethod

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

推荐答案

你可以把你所有的方法到对象。

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

这篇关于JavaScript模块模式中的方括号表示法和范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆