这是本人比较习惯的javascript面象对象写法,里面有一些关于包、类、抽象函数、继承、重载的一些写法,供有兴趣的朋友参考,也期待宝贵的建议。
代码中实现的是一个“车辆”类,并用Car和Tank继承,其中Tank具有攻击性。最后以console的方式表现了三个对象之间的攻击效果。
//定义包(命名空间)示例 com={}; com.hoverlees={}; /** * 车辆基类 * @param x 当前x坐标 * @param y 当前y坐标 * @constructor */ com.hoverlees.Vehicle=function(x,y){ this.life=100; this.maxLife=100; this.speed=1; this.x=x; this.y=y; this.destX=x; this.destY=y; this.isDead=false; } /** * 设置目标坐标 */ com.hoverlees.Vehicle.prototype.setDestination=function(x,y){ this.destX=x; this.destY=y; } /** * 移动 */ com.hoverlees.Vehicle.prototype.move=function(){ console.log("vehicle moving to "+this.destX+","+this.destY); } /** * 攻击对象,此函数为抽象函数 * @param target com.hoverlees.Vehicle */ com.hoverlees.Vehicle.prototype.attack=function(target){ throw "Vehicle::attack should be implemented"; } com.hoverlees.Vehicle.prototype.die=function(){ this.isDead=true; console.log("die"); } /** * 普通私家车 */ function Car(x,y){ //调用父类构造函数示例 com.hoverlees.Vehicle.call(x,y); this.life=50; this.maxLife=50; } Car.prototype=new com.hoverlees.Vehicle(); Car.prototype.constructor=Car; /** * 函数重载示例 */ Car.prototype.move=function(){ console.log("car("+this.life+"/"+this.maxLife+") moving to "+this.destX+","+this.destY); } /** * 抽象函数实现示例,私家车的攻击表现为跟随目标 * @param target com.hoverlees.Vehicle */ Car.prototype.attack=function(target){ //调用父类函数 this.setDestination(target.x,target.y); } /** * 坦克 * @param x * @param y * @param maxLife 最大生命值 * @param attackPoint 攻击力 * @constructor */ function Tank(x,y,maxLife,attackPoint){ com.hoverlees.Vehicle.call(x,y); this.maxLife=maxLife; this.life=maxLife; this.attackPoint=attackPoint; /** * @type {com.hoverlees.Vehicle} */ this.attackTarget=null; } Tank.prototype=new com.hoverlees.Vehicle(); Tank.prototype.constructor=Tank; Tank.prototype.move=function(){ console.log("tank("+this.life+"/"+this.maxLife+") moving to "+this.destX+","+this.destY); } /** * 攻击车或坦克 * @param target com.hoverlees.Vehicle */ Tank.prototype.attack=function(target){ if(target.isDead) return; console.log("Tank("+this.life+"/"+this.maxLife+") attacking target("+target.life+"/"+target.maxLife+")"); target.life-=this.attackPoint; if(target.life<=0) target.die(); } var b=new Car(200,200); b.setDestination(1,2); var c=new Tank(300,300,100,10); var d=new Tank(300,300,200,30); setInterval(function(e){ if(!b.isDead) b.move(); if(!c.isDead) c.attack(d); if(!d.isDead) d.attack(c); if(c.isDead && !b.isDead){ d.attack(b); } },1000)