Subtle Nuances of Javascript Inheritance: Child.prototype = Parent.Prototype vs. Child.prototype = new Parent()
In Javascript, inheritance is often implemented using the prototype mechanism. The key distinction between these two common approaches lies in their impact on the proto property of the child object.
When using Child.prototype = Parent.Prototype, both the child and parent prototypes point to the same object. This means that any changes made to the child's prototype will also affect the parent's prototype.
However, when using Child.prototype = new Parent(), a new object is created that inherit from the parent's prototype. This ensures that the child's prototype is isolated from the parent's, allowing for independent modifications without impacting the parent.
Effects on Instance Properties
In the example provided, the issue arises when setting instance properties within the child constructor:
this.hitBox.width = oImg.width; this.hitBox.height = oImg.height;
With Child.prototype = Parent.Prototype, these properties are added directly to the child's prototype, which is also the parent's prototype. As a result, the console.log(this) in the child constructor shows proto: Spaceship because the prototype is now set as Spaceship.
Solution: Using Object.create
To avoid this issue, it is recommended to use Object.create(Parent.prototype):
Spaceship.prototype = Object.create(GameObject.prototype);
This strategy creates a new object that inherits from the parent's prototype while maintaining its own independent prototype. Instance properties added to the child's prototype will not affect the parent's.
Comparison to instanceof
In the case of checking for inheritance using object instanceof GameObject, it is important to note that Child.prototype = Parent.Prototype will fail this test since the child's prototype is not an instance of GameObject. In contrast, Child.prototype = new Parent() will pass the test as expected.
Recommendation
For robust and isolated inheritance in Javascript, it is generally preferred to use Child.prototype = Object.create(Parent.prototype) rather than Child.prototype = Parent.Prototype.
The above is the detailed content of JavaScript Inheritance: Child.prototype = Parent.Prototype vs. Child.prototype = new Parent() - Which Approach is Better?. For more information, please follow other related articles on the PHP Chinese website!