假设我有两个类 Entity 和 Player 的构造函数。 (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 原型(prototype)链添加一个无用的对象,我永远不会使用它,因为我不希望玩家共享一个“速度”变量。它可能对每个玩家都是独一无二的。
Player.prototype = Entity.prototype
也不起作用,因为 Entity 对象也变成了 instanceof Player
...
有没有一种方法可以模拟继承,只是让 instanceof 起作用,而不在原型(prototype)链中引入无用的对象?
最佳答案
Player.prototype = Object.create(Entity.prototype);
这将创建一个具有指定原型(prototype) (Entity.prototype) 和属性的新对象。
在ES6中,可以像java一样使用class-关键字和extends关键字。
关于javascript - 原型(prototype)继承和instanceof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35535631/