This line right here is your problem:
Player.prototype = Person.prototype;
You want the prototype for Player
to inherit from Person
's prototype, but not make them equal. Currently, your code makes the Player
and Person
prototypes reference equal, so any changes to Player.prototype
also affect the Person.prototype
(effectively making them indistinguishable).
You're looking for:
Player.prototype = Object.create(Person.prototype);
Object.create
instantiates a new object with a given prototype without actually calling the constructor (unlike a regular new Person()
call would do). This allows you to get a new object inheriting the Person
prototype, which you can then modify for the specifics of a Player
.
EDIT: As suggested in the comments by Siddarth, an even better solution would be to set the constructor
through a property descriptor:
Player.prototype = Object.create(Person.prototype, {
constructor: { value: Player }
});
This way, the newly created prototype will have its constructor
property made non-configurable, non-enumerable and non-writable. This prevents you from accidentally changing it afterwards through an assignment (e.g. Player.prototype.constructor = Foo
) and it won't show up in Object.keys
or a for..in
loop. Normally, this shouldn't matter much but it's a good practice.