0

因此,我正在阅读 John Resig 的 JavaScript Ninja 的秘密,并观看 Doug Crockford 关于 ECMAScript 5 的演讲,查看浏览器对 Object.create() 的支持,以及如何最好地使用 JavaScript 中的对象和继承。

我想出了一种我认为创建对象和继承的简单方法,我只是想问一下我是否完全忽略了一些陷阱等。好的,这里有一些代码:

// OOP - game enemy example

// Let's create a base enemy type, and two enemies that inherit from it.
// Enemies must be kept track of (how many have been "instantiated").
// Enemies will need to have HP, speed and names.
// Enemies will need to be able to take damage independent of other enemies.
// It must be possible to cause all enemies to double HP and speed or halve them.

// Enemy
function Enemy (name) {
  var enemy = {};
  enemy.name = name;
  enemy.currentHp = Enemy.baseHp * 100; // basic enemies have 100 hit points
  enemy.currentSpeed = Enemy.baseSpeed * 5; // basic enemies have 5 speed
  enemy.hp = Enemy.hp;
  enemy.speed = Enemy.speed;
  Enemy.count += 1; // Count each instantiated bad guy
  return enemy;
}
// Enemy properties (these are the same for all enemies)
Enemy.count = 0;
Enemy.baseHp = 1; // if we change this to 1.3 or .5 all the enemies in the game will be boosted or deminished...
Enemy.baseSpeed = 1; // ...same here.
// getter and setter for hp
Enemy.hp = function (value) {
  if (!!value) {
    return this.currentHp = ((this.currentHp * Enemy.baseHp) + value);
  }
  return this.currentHp * Enemy.baseHp;
};
// getter and setter for speed
Enemy.speed = function (value) {
  if (!!value) {
    return this.currentSpeed = ((this.currentSpeed * Enemy.baseSpeed) + value);
  }
  return this.currentSpeed * Enemy.baseSpeed;
};

// Trio enemy
function Trio (name1, name2, name3) {
  var trio = Enemy();
  trio.name = [name1, name2, name3];
  trio.currentHp = Enemy.baseHp * 30; // trios have less hp...
  trio.currentSpeed = Enemy.baseSpeed * 10; // ...but more speed
  Enemy.count += 3; // they raise the enemy count by three
  return trio;
}

// Boss enemy
function Boss (name) {
  var boss = Enemy(null);
  boss.name = name;
  boss.currentHp = Enemy.baseHp * 300; // Bosses have lots of hp...
  boss.currentSpeed = Enemy.baseSpeed * 1; // ...but they're super slow
  Enemy.count += 1;
  return boss;
}

那么,我是否遗漏了什么,或者我是否符合我的标准?使用普通函数而不是构造函数和“new”是否会对性能产生巨大影响?还是 Object.create ?我以某种方式使内存过载?我很确定对于我只使用 Enemy.someMethod 在内存中创建一次的每个敌人的任何功能都是相同的。希望得到一些反馈。如果我需要调整诸如 enumerable 或 writable 之类的属性,我可以在我的“假”构造函数中使用 Object.defineProperties (或 Object.create 带有两个参数),对吗?像这样...

// Flyer
function Flyer (name) {
  var flyer = Enemy();
  // Using Object.defineProperties to assign attributes to properties.
  Object.defineProperties(flyer, {
    name: {value: name, enumerable: true},
    currentHp: {value: Enemy.baseHp * 50, writable: true, enumerable: true},
    currentSpeed: {value: Enemy.baseSpeed * 3, writable: true, enumerable: true},
  });
  Enemy.count += 1;
  return flyer;
}

很想听听你的想法。

4

0 回答 0