zoukankan      html  css  js  c++  java
  • 面向对象的JavaScript(一) — 类及类的继承

        看到很多做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("飞飞"1000100);//实例化出一个人物
        var rabbit = new Role("兔子"40050); //实例化出一个怪物
        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(
    thisnew 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("小小"10000500200100,0);
        
    var dog = new Monster("狗狗"60020);
        xiaoxiao.physicalAttack(dog);
        xiaoxiao.magicAttack(dog);
        alert(
    "狗狗当前HP:" + dog.hp);
        alert(
    "小小当前Exp:" + xiaoxiao.exp);

    代码中做了详细的注释,就不在废话
  • 相关阅读:
    hdu 1028 母函数 一个数有几种相加方式
    第m个全排列
    大数处理
    并查集
    KMP算法及KMP算法的应用(POJ2406)
    算法---分治法
    末学者笔记--NTP服务和DNS服务
    末学者笔记--NFS服务和DHCP服务讲解
    末学者笔记--SSHD服务及SCP用法
    末学者笔记——SAMBA服务、FTP服务讲解
  • 原文地址:https://www.cnblogs.com/farmer/p/1563131.html
Copyright © 2011-2022 走看看