如何授予类方法对对象实例的访问权限

时间:2019-01-25 23:56:29

标签: instance javascript-objects class-method

我正在尝试创建一系列表示游戏中角色的对象。每个对象都需要访问一组类方法,这些类方法表示每个角色可以执行的基本非唯一操作(运行,战斗,防御等)。每个动作都应该能够访问每个对象中的值,例如角色名称,年龄或武器。我知道我可以使用自己的方法初始化每个对象以访问对象实例,但是对于每个字符全局共享的基本命令,应该有一种更有效的方式来实现。

    //create character object 
    var Character = new Character(name, age, weapon, armor, item);

    //initialize instances of character object
    function Character(name, age, weapon, armor, item) {
        this.name = name;
        this.age = age;
        this.weapon = weapon;
        this.armor = armor;
        this.item = item;
    };
        //create new characters from character object model
        var knight = new Character(Shawn, 29, Broadsword, ChestPlate, 
        HealthPotion);

        var mage = new Character(Jessica, 28, Staff, Robe, ManaPotion);

        var thief = new Character(Cody, 28, Knife, Vest, HealthPotion);

        //create class methods
        Character.prototype.attack = function(name, weapon) {
          alert(this.name + " " + "attacked using their" + " " + 
          this.weapon + "!"); 
        }

        Character.prototype.defend = function(name) {
          alert(this.name + " " + "holds their defenses!"); 
        }


        Character.prototype.useItem = function(name, item) {
          alert(this.name + " " + "used" + " " + this.item + "!"); 
        }

        Character.prototype.run = function(name) {
          alert(this.name + " " + "has fled the battle"); 
        }

        attack(knight); 

被称为攻击时没有任何反应。

0 个答案:

没有答案