第 7 章,eloquentJavaScript:栩栩如生的世界

Chapter 7, eloquent JavaScript: LifelikeWorld

我一直在读这本书,并且在经历了很多困难和其他资源后,终于熬到了这里(它本身就太难了,但它仍然非常有用,还有其他资源)。

这是我觉得很难理解的代码:

function LifelikeWorld(map, legend) {
  World.call(this, map, legend);
}
LifelikeWorld.prototype = Object.create(World.prototype);

var actionTypes = Object.create(null);

LifelikeWorld.prototype.letAct = function(critter, vector) {
  var action = critter.act(new View(this, vector));
  var handled = action &&
    action.type in actionTypes &&
    actionTypes[action.type].call(this, critter,
                                  vector, action);
  if (!handled) {
    critter.energy -= 0.2;
    if (critter.energy <= 0)
      this.grid.set(vector, null);
  }
};

var actionTypes = Object.create(null); // actionTypes 创建了一个 null 对象吗?

var handled,我无法理解那个变量,我理解这些概念,它是否检查 action、actiontype 是否为真?并且,actionTypes[action.type] => actionType 不是空对象?

Object.create(null) 创建一个以 null 为原型的对象。这意味着与对象字面量 ({}) 或 new Object() 不同,它不会从 Object.prototype.

继承属性

handled 变量为 trueaction 变量为真时,actionTypes 变量包含键 action.typeactionTypes[action.type].call(this, critter, vector, action) returns 真实值。