原型继承和instanceof

Prototypal Inheritance and instaceof

假设我有两个构造函数用于 class 实体和播放器。 (Player 打算从 Entity 继承)

var Entity = function(speed) { this.speed = speed; }

var Player = function(name) { Entity.call(this, 10); this.name = name; }

assert(new Player('p1') instanceof Entity === false)

为了让新的 Player 对象成为 Entity 的实例,我通常会做类似...

Player.prototype = new Entity();

但这会向 Player 原型链添加一个无用的对象,我永远不会使用它,因为我不希望玩家共享单个 'speed' 变量。它可能对每个玩家都是独一无二的。

Player.prototype = Entity.prototype

也不起作用,因为 Entity 对象也变成了 instanceof Player...

有没有一种方法可以模拟继承,只是让 instanceof 工作,而不在原型链中引入无用的对象?

ES5方式是使用Object.create(),ES6方式是使用class关键字:

class Entity {
  constructor(speed) { ... }
}

class Player extends Entity {
  constructor(name) {
    super(10);
    this.name = name;
  }
}
Player.prototype = Object.create(Entity.prototype);

这将创建一个具有指定原型 (Entity.prototype) 和属性的新对象。

参考:Object.create()

在ES6中,可以使用class关键字和类似java的extends关键字。