Javascript:更改test()方法名称

时间:2013-11-26 18:46:50

标签: javascript

好的,我正在制作一个基于文本的游戏,我一直在使用这样的开关命令

switch(true){
case /run/.test(g1):
    prompt("run");
    break;
}

我的问题是我可以更改test()方法的名称,如此

switch(true){
case /run/.act(g1):
    prompt("run");
    break;
}

我想如果我创建了一个像这样的函数它可以工作

function act(str){
test(str);
return;
}

但它没有...任何帮助都会很好。

编辑:固定开关语句

2 个答案:

答案 0 :(得分:1)

所以/run/是一个正则表达式对象。它有一个名为test的方法。它没有方法行为,因此你不能在它上面调用act()。

您需要使用原型:

switch{
     case /run/.act(g1):
     prompt("run");
     break;
}
RegExp.prototype.act = function (str) {
    return this.test(str);
}

Here是原型的解释。

答案 1 :(得分:0)

如果您真的需要这样做(请参阅What is the XY problem?),那么您可以向prototype对象添加RegExp

var regex = /fo+/;
var str = 'fooooooooooooooo';

regex.test(str); //true

RegExp.prototype.act = function(str) {
    if (str == 'fooooooo' && this.test(str)) {
        return true;
    } else {
        return false;
    }
}

regex.act(str); //false (str is not 'fooooooo')

同样,您可以通过简单地返回this.test()来制作别名(但请,请不要 - 它可以正常工作):

RegExp.prototype.act = function(str) {
    return this.test(str);
}