Overriding Inheritance Model: Child.prototype = Parent.Prototype vs. Child.prototype = new Parent()
In JavaScript inheritance, the relationship between child and parent objects is established through prototype chaining. Typically, developers define inheritance using Child.prototype = new Parent(). However, an alternative approach, Child.prototype = Parent.Prototype, also exists. This article examines the differences between the two and provides an explanation for an apparent discrepancy that arises when using the latter.
Difference in Execution
Child.prototype = new Parent() creates a new object as a prototype for the child class (Child) and sets its prototype to the parent class (Parent). This newly created object inherits all properties and methods from the parent.
On the other hand, Child.prototype = Parent.Prototype does not create a new object. Instead, it simply references the prototype of the parent class. This means that child and parent classes share the same prototype object and any changes made to one will affect the other.
Discrepancy in .proto Property
In the provided example, the discrepancy arises because the this.hitBox lines attempt to add properties to the this object, which in the case of Spaceship is the newly created prototype. However, when the prototype (this.hitBox) is later assigned to GameObject.prototype, GameObject's prototype is overwritten, and the properties that were added to Spaceship's prototype are lost. This explains why the this.proto property in Spaceship is set to Spaceship instead of GameObject.
Recommended Inheritance Method
For inheritance to function correctly, it's recommended to use Child.prototype = new Parent() instead of Child.prototype = Parent.Prototype. The former approach creates a separate prototype object for the child class, while the latter can lead to unexpected inheritance behavior.
To mitigate the issue in the provided example, one can use Object.create(GameObject.prototype) to create a new object as a prototype for Spaceship. This object will have the same properties and methods as GameObject's prototype but will not be overwritten when GameObject's prototype is modified.
The above is the detailed content of Child.prototype = Parent.Prototype vs. Child.prototype = new Parent(): Why Choose One Over the Other in JavaScript Inheritance?. For more information, please follow other related articles on the PHP Chinese website!