如何使用" set"设置新属性方法

时间:2018-05-13 09:51:44

标签: javascript

我想用" setWeapon"设置武器。通过创造"武器"财产也。示例呼叫:" archer.setWeapon(弓);"



 function Weapon(name,damage) {
        this.name = name;
        this.damage = damage;
    }
    Weapon.prototype.toString = function () {
        return this.name + this.damage + " damage"; // method to show weapon
    };
    var bow = new Weapon('Golden bow, ', 20); // create weapon 
    function Character() {
        this.health = 100;
        this.basicDamage = 10;
        this.toString = function () {
            return this.name + this.type; // add and show weapon bow
        };
    Character.createArcher = function () { // create hero 
        var hero = new Character;
        hero.name = "Legolas";
        return hero;
    };
    Character.setWeapon = function () { 
        var weapon = new Character();
        weapon.type = Weapon;
        return weapon;
    };
    var archer = new Character.createArcher();
    archer.setWeapon(bow); // set the selected weapon
    console.log(archer.toString());




1 个答案:

答案 0 :(得分:1)

一种方法是使用setWeapon扩展Character的原型,setter只设置值 - 它们不返回值。你可以为此编写getWeapon()。这样你传递实际武器并分配给射手。希望有所帮助。 (武器是一个对象,所以你可以访问archer.weapon.type)

var bow = new Weapon('Golden bow, ', 20); // create weapon 

Character.prototype.setWeapon = function (weapon) { 
    var me = this;
    me.weapon = weapon; // set the weapon
};

var archer = new Character.createArcher();
archer.setWeapon(bow); // set the selected weapon
console.log(archer.toString()); // add to string also property weapon