这几天早上看了一下红宝书中对象一章,看到了用构造函数和原型模式来创建实例,就想了一下哪些场景用这个比较好。想到了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");
之前同事在项目中也是这么干的。但场景不一样,项目中的场景只需要一个实例,所以用原型模式的话,调用原型对象中的方法时理论上比直接调用实例中的方法要慢。