自定义类,以及覆盖接口toString方法
2.4 自定义类,以及覆盖接口toString方法
用opp的话来说,object是所有类的基类。as1.0 和as2.0有不同的方法定义类,但是使用方法都是一样的:
var x = new myClassName(<paras>这样x就是 myClassName 类的实例了。比如最基本的:
var对于每个类来说,有一个方法相当重要。自定义的类一定要覆盖该方法:
Object. toString他是一个系统接口,要求返回一个字符串。在一个object数据参与字符串运算的时候,系统都会自动调用实例.toString()方法来完成转换。一般来说,由于没有覆盖这个接口,转换结果都是: "[object Object]"之类的 定义了这个接口接口之后,在使用
trace( myInstance )的时候 myInstance.toString() 就会发动——方便啊~~~ 这里给出一个自定义类的例子:
(as1.0)我们定义一个Enemy类,他会自动产生属性 id x y hp ,并且覆盖toString接口。
注意构造函数中的this。
function Enemy(x,y,hp){
this.id = Enemy.id ++;
this.x = x;
this.y = y;
this.hp = hp;
}
Enemy.id = 0;
Enemy.prototype.toString =function(){
return this.id +" x:" + this.x +" y:" + this.y + " hp:" + this.hp;
} var myEnemy = new Enemy(10,23,100);
trace(myEnemy);
这对你的调试无疑带来了巨大的方便。而且在复合类的时候,复合类的 toString方法可以使用成员类的 toString()返回的 string:
function Dragon(x,y,hp){
this.enemy = new Enemy(x,y,hp);
}
Dragon.prototype.creatureName = "Dragon"
Dragon.prototype.toString = function (){
var str = this.creatureName ;
str += this.enemy;
return str;
}
trace( new Drago