不能扩展 String 原型?

Can't extend String prototype?

我正在尝试在 Actionscript 3 中扩展字符串 class。我的目标是自动在字符串周围添加标签。

代码:

String.prototype.addTags = function(t1:String, t2:String) : String {
    return t1 + this + t2;
}

然后调用函数:

var str:String = "hello";
str.addTags("<b>", "</b>");


// expected output: <b>hello</b>
trace(str);

这会产生以下错误:

1061:通过静态类型 String 的引用调用可能未定义的方法 addTags。

这是个坏主意。而且你不能扩展原始类型。如果你创建 class-utility 来做任何你想做的事,那就更好了。例如:

package {
    public class StringUtil {
        public static function addTags(value:String, leftTag:String, rightTag:String):String {
            return leftTag + value + rightTag;
        }
    }
}

P.S。这只是例子。有许多不同的方法可以实现您想要的。

如果你想使用 "prototype" 来做到这一点,你可以将你的字符串(或者你想要的数字)向上转换为 Object,如下所示:

Object.prototype.addTags = function(t1:String, t2:String):String {
    return t1 + this + t2;
}

var str:String = 'hello';
    str = Object(str).addTags('<b>', '</b>');

trace(str);                                     // gives : <b>hello</b>

trace(Object('world').addTags('<u>', '</u>'));  // gives : <u>world</u>

trace(Object(2015).addTags('<p>', '</p>'));     // gives : <p>2015</p>

希望能帮到你。

我同意其他一些认为这是 "bad idea" 的答案。但是,只是为了回答您的问题,原始代码的问题很简单,就是您没有对 addTags() 的返回值做任何事情。这应该有效:

String.prototype.addTags = function(t1:String, t2:String):String {
    return t1 + this + t2;
}

var str:String = "hello";
str = str.addTags("<b>", "</b>");

trace(str); // <b>hello</b>

尽管在 "strict mode" 中你会在 str.addTags() 上得到编译错误,因为 addTags() 不是编译器已知的 String 方法。您可以通过使用动态引用或强制转换为动态的 Object 来解决此问题:

str = Object(str).addTags("<b>", "</b>");

Array class 已经是动态的,所以这就是为什么在使用添加到数组原型的方法时不会出现此编译错误的原因。

同样,我同意其他人的看法,有 "better" 种方法可以做到这一点。 (即更适合 AS3 语言设计的方式。)