面试题答案
一键面试1. 使用构造函数
function Character(health) {
this.health = health || 100;
this.attack = function() {
console.log('Attacking!');
};
}
function Warrior(strength) {
Character.call(this);
this.strength = strength;
}
Warrior.prototype = Object.create(Character.prototype);
Warrior.prototype.constructor = Warrior;
Warrior.prototype.specialAttack = function() {
console.log('Warrior special attack!');
};
function Mage(mana) {
Character.call(this);
this.mana = mana;
}
Mage.prototype = Object.create(Character.prototype);
Mage.prototype.constructor = Mage;
Mage.prototype.castSpell = function() {
console.log('Mage casts a spell!');
};
2. 使用Object.create()
const characterPrototype = {
health: 100,
attack: function() {
console.log('Attacking!');
}
};
function createWarrior(strength) {
const warrior = Object.create(characterPrototype);
warrior.strength = strength;
warrior.specialAttack = function() {
console.log('Warrior special attack!');
};
return warrior;
}
function createMage(mana) {
const mage = Object.create(characterPrototype);
mage.mana = mana;
mage.castSpell = function() {
console.log('Mage casts a spell!');
};
return mage;
}
3. 性能影响及优化
- 构造函数:每次通过构造函数创建新实例时,都会为每个实例重新创建
attack
等方法,在大规模创建角色实例时,会占用较多内存。优化方法是将共享方法放在原型链上,如上面代码中的Warrior.prototype.attack
等,这样所有实例共享这些方法,减少内存开销。 Object.create()
:优点是直接基于现有原型创建对象,避免了构造函数中不必要的函数重复创建。但在创建复杂对象时,代码可能会显得比较冗长。优化时可以将公共逻辑封装成函数,提高代码的复用性。
总的来说,在大规模创建角色实例时,将共享方法放在原型链上能显著提高性能,无论是使用构造函数还是Object.create()
方法,合理利用原型链是优化内存和提高性能的关键。