1. 程式人生 > >用建構函式和原型模式動態建立例項

用建構函式和原型模式動態建立例項

這幾天早上看了一下紅寶書中物件一章,看到了用建構函式和原型模式來建立例項,就想了一下哪些場景用這個比較好。想到了Dota。

function Hero(name, sex, skill1, skill2, skill3) {
    this.name = name;
    this.sex = sex;
    this.skill1 = skill1;
    this.skill2 = skill2;
    this.skill3 = skill3;
    this.weapon = [];

    this.ultimateSkill = function (ultimateSkill) {
        console.log("the hero [" + this.name + "] start ultimate skill: " + ultimateSkill);
    };

    if(typeof Hero.initialized == "undefined"){
        Hero.prototype.buyWeapon = function (weaponName) {
            this.weapon.push(weaponName);
        };
        Hero.prototype.updateSkill = function () {
            if(!this.skill1){
                this.skill1 = true;
            }else if(!this.skill2){
                this.skill2 = true;
            }else if(!this.skill3){
                this.skill3 = true;
            }
        };
        Hero.prototype.attack = function (weapon) {
            console.log("the hero [" + this.name + "] attack enemy by " + weapon);
        };
        Hero.prototype.go = function () {
            console.log("the hero [" + this.name + "] go ahead");
        };
        Hero.prototype.back = function () {
            console.log("the hero [" + this.name + "] go back");
        };
        Hero.prototype.moveLeft = function () {
            console.log("the hero [" + this.name + "] move left");
        };
        Hero.prototype.moveRight = function () {
            console.log("the hero [" + this.name + "] move right");
        };
    }
    Hero.initialized = true;
}

var xiuDou = new Hero("xiudou", "girl", false, false, false);
var longQiShi = new Hero("longqishi", "dragon", false, false, false);

xiuDou.go();
longQiShi.go();

xiuDou.buyWeapon("knife");
xiuDou.buyWeapon("axe");
longQiShi.buyWeapon("hammer");
longQiShi.buyWeapon("bows and arrows");
longQiShi.buyWeapon("sword");

xiuDou.attack(xiuDou.weapon[0]);
longQiShi.attack(longQiShi.weapon[1]);

xiuDou.ultimateSkill("fire");
longQiShi.ultimateSkill("ice");

 

 

之前同事在專案中也是這麼幹的。但場景不一樣,專案中的場景只需要一個例項,所以用原型模式的話,呼叫原型物件中的方法時理論上比直接呼叫例項中的方法要慢。