看到很多做ASP.NET开发的JS水平都很差,所以想写一个面向对象的JavaScript系列,希望对JS新手有所帮助。不知道能否坚持下去。今天从类(非静态类)及类的继承开始。我用游戏中的角色(玩家,怪物)来做示例。
首先是角色类,具有基本属性 Name,HP,PhysicalDamage和基本方法PhysicalAttack
以下为引用的内容:
//角色
//类名:Role
function Role(name, hp, pd) {
this.Name = name; //属性-名字
this.HP = hp; //属性-生命
this.PhysicalDamage = pd; //属性-物理攻击力
//方法-物理攻击(r:被攻击目标)
this.PhysicalAttack = function(r) {
alert(this.Name + " 物理攻击 " + r.Name + "\r\n HP - " + this.PhysicalDamage);
r.HP = r.HP - this.PhysicalDamage;
}
}
var feifei = new Role("飞飞", 1000, 100);//实例化出一个人物
var rabbit = new Role("兔子", 400, 50); //实例化出一个怪物
feifei.PhysicalAttack(rabbit); //发起物理攻击
alert("兔子当前HP:" + rabbit.HP);
由于Role类不能满足需要,我们新建两个类Player,Monster继承Role
以下为引用的内容:
//普通怪物 继承 Role
function Monster(name, hp, pd) {
Role.apply(this, arguments); //通过apply实现继承,强大的apply使Monster具备了Role的所有属性与方法,apply和call是个神奇的东西,大家有兴趣自己谷歌。
}
//玩家 继承 Role
function Player(name, hp, mp, pd, md, exp) {
Role.apply(this, new Array(name, hp, pd)); //通过apply实现继承,并传参赋值
this.MP = mp; //属性-魔法值
this.MagicDamage = md; //属性-魔法攻击力
this.Exp = exp; //属性-经验值
//方法-魔法攻击(r:被攻击目标)
this.MagicAttack = function(r) {
if (this.MP > 9) {
alert(this.Name + " 魔法攻击 " + r.Name + "\r\n HP - " + this.PhysicalDamage + "\r\n MP - 10 , Exp + 10");
r.HP = r.HP - this.MagicDamage;
this.MP -= 10;
this.Exp += 10;
}
else
alert("魔法值不够");
};
//这里重写 PhysicalAttack 方法,很不方便!不知道有好的方法没???
this.PhysicalAttack = function(r) {
alert(this.Name + " 物理攻击 " + r.Name + "\r\n HP - " + this.PhysicalDamage + "\r\n Exp + 10");
r.HP = r.HP - this.PhysicalDamage;
this.Exp += 10;
};
}
var xiaoxiao = new Player("小小", 10000, 500, 200, 100,0);
var dog = new Monster("狗狗", 600, 20);
xiaoxiao.PhysicalAttack(dog);
xiaoxiao.MagicAttack(dog);
alert("狗狗当前HP:" + dog.HP);
alert("小小当前Exp:" + xiaoxiao.Exp);
代码中做了详细的注释,就不在废话。
© CopyRight 2008-2010, WWW.JSJGZ.CN All Rights Reserved
CopyRight 2008-2010 计算机故障网版权所有 闽ICP备09000710号