It never explained why you became weird behavior with this.hitBox (I think you were trying to say).
If you inherit by calling the parent constructor to create the prototype, this parent constructor runs once to create an instance of the parent type, and then all instances of the child type will use this instance as their prototype.
The problem is that if this constructor has any lines that assign mutable objects to this , then these objects will be the properties of this prototype, and any changes to these objects will be displayed in all instances of the child type:
Spaceship.prototype = new GameObject(); Spaceship.prototype.constructor = Spaceship; var sps1 = new Spaceship(); var sps2 = new Spaceship(); sps1.hitBox.x = 9; sps2.hitBox.x = 12; console.log(sps1.hitBox.x);
(there are other similar problems with “calling the constructor to make a prototype”, but I just leave it here at this point)
@ The idea of using Object.create(baseObject) is the first step to solving this problem. It creates a new object, the prototype of which is baseObject , but without the content created in the constructor (this is good, but it must be taken into account. Read on ...).
As I said, this will create an object in which the initialization logic of the parent constructor never starts, but in most cases this logic is related to the functionality of the object. So, there’s something else you need to do to make the child constructor invoke the parent constructor:
function Spaceship(oImg, x, y) { // call parent constructor on this object and pass in arguments. // you could also use default values for the arguments when applicable GameObject.call(this, oImg, x, y); // remainder of Spaceship constructor... }
This ensures that the parent constructor logic runs separately for each new Spaceship and performs the necessary initialization tasks.
Jlrishe
source share