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