ActionScript3 - 扩充String的原型

时间:2013-02-20 12:33:07

标签: string actionscript-3 prototype

在AS2中,我可以执行以下操作:

String.prototype.startsWith = function(s){
     return this.indexOf(s) == 1
}

因此,每个String对象都可以使用startsWith

var s = "some string to test with";
s.startsWith("some") // returns true

并使用很棒的酷工具库来完成它:

var s = "some @VAR string";
s.startsWith("some");//returns true
s.endsWith("ing");//returns true
s.contains("@");//returns true
s.dataBind({VAR: "awsome"})// returns 'some awsome string'
s = "b";
s.isAnyOf("a","b","c"); //true, because "b" is one of the options
s.isInArr(["a","b","c"]); //true, because "b" is in the passed array
var o = { foo: function(i) { return "wind " + i } }
s = "foo";
f.call(o,3) //returns "wind 3" because method foo is ivoked on o with 3
f.apply(o,[3]) //returns "wind 3" because method foo is ivoked on o with 3
var a1 = [], a2 = []
s.push(a1,a2) // pushes s into a1 and a2

等等,有许多很酷的东西可以使编码变得更有趣(并且在使用时非常快速)

这不只是关于String,我有数字,日期,布尔等的实用工具。

这是我试过的:

[Test]
public function test_stringPrototype()
{
    String.prototype.startsWith = function(s):Boolean
    {
        return return this.indexOf(s) == 1;
    }

    assertTrue( !!String.prototype.startsWith ) //and so far - so good ! this line passes

    var s:String = "some str";
    assertTrue(!!o.startsWith ) //and this won't even compile... :(
}

这甚至不会编译,更不用说测试通过或失败了...... 错误:Access of possibly undefined property startsWith through a reference with static type String.

在AS3中如何做到这一点?

2 个答案:

答案 0 :(得分:1)

你总是可以使用实用程序类来收集所有这些方法并处理字符串,例如

package utils
{
    public class StringUtils
    {
        public static function startsWith(input:String, test:String):Boolean
        {
            return input.indexOf(test) == 0;
        }
    }
}

用法:

trace(StringUtils.startWith("My string", "My"));

或作为“全球”功能:

package utils
{
    public function startsWith(input:String, test:String):Boolean
    {
        return input.indexOf(test) == 0;
    }
}

用法:

trace(startWith("My string", "My"));

最好的问候

答案 1 :(得分:0)

是的,当然,使用变量名的字符串表示:“startsWith”;示例下来

        String.prototype.traceME = function():void
        {
            trace(this);
        }

        var s:String = "some str";
        s["traceME"]();

其他方法:

            var s:Object = new String("some str");
            s.traceME();