1

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

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

因此,startsWith可用于每个 String 对象

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

等等,还有很多很酷的东西,让编码变得更有趣(并且巧妙地使用时速度极快)

这不仅仅是关于字符串,我还有用于数字、日期、布尔值等的实用程序。

这是我尝试过的:

[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 中的实现方式是什么?

4

2 回答 2

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

此致

于 2013-02-20T14:03:11.753 回答
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();
于 2013-02-20T12:51:45.770 回答