具有变量名称和别名方法的方法

时间:2015-07-01 10:44:05

标签: javascript

我已将此问题从代码审核https://codereview.stackexchange.com/questions/95205/methods-with-variable-names-and-alias-methods

中移除

请阅读代码审核答案和评论

我正在编写一个根据变量运行函数的javascript代码。 让我们假设有两个域叫做(example.com和foo.com)," example.com"有子域名(a.example.com和b.example.com),子域名有另一个主域名(www.a.com和www.b.com)我想要做的是运行一个基于域变量的函数,为此,我创建了一个对象,并将每个域的方法放在其中,以便我可以通过变量名称调用它,并且我还编写了"别名函数"对于子域及其maindomains(因为example.com函数适用于它的子域)

所以这是代码:

var subdomains = {
example_com:function(){
    // do stuff related to example.com and it's subdomains (a.example.com and b.exmple.com)
    // and their main domains (www.a.com and www.b.com).
},
www_foo_com:function(){
    // do stuff related to www.foo.com
},
// alias to call example_com() when any of it's subdomains (a.example.com and b.exmple.com)
// or their main domain (www.a.com and www.b.com).
a_example_com:function(){
    // alias to a.example.com
    this.example_com();
},
b_example_com:function(){
    // alias to b.example.com
    this.example_com();
},
www_a_com:function(){
    // alias to www.a.com
    this.example_com();
},
www_b_com:function(){
    // alias to www.b.com
    this.example_com();
}
};
// now i can call the function depending on the domain variiable

var domain = "a.example.com"; //  or it can be b.example.com, www.a.com, www.b.com, www.foo.com

var func_name = domain.replace(/\./g,"_"); // Results: a_example_com

var run = subdomains[func_name](); // run the function related to the domain or subdomain

代码工作正常并且做了预期的但我希望能够节省我花时间和精力将别名函数写入所有子域的方法,因为有域有20个子域!想象一下为域及其主域编写20个别名函数(40个函数)

1 个答案:

答案 0 :(得分:0)

您可能希望寻找更好的Regex来获得您想要的功能。 例如,让www.example.com xyz.example.com返回example

var func_name = domain.replace(/.*\.([a-z]+)\.com/,"$1"); // only for .com TLDs