Home  >  Article  >  Web Front-end  >  Why is Child.prototype = Parent.prototype a Bad Idea for JavaScript Inheritance?

Why is Child.prototype = Parent.prototype a Bad Idea for JavaScript Inheritance?

DDD
DDDOriginal
2024-11-13 16:09:02714browse

Why is Child.prototype = Parent.prototype a Bad Idea for JavaScript Inheritance?

Inheritance in JavaScript: Why not Use Child.prototype = Parent.prototype?

In JavaScript, inheritance can be achieved through delegation, using Child.prototype = new Parent(); to link the child prototype to a new instance of the parent prototype. However, setting Child.prototype = Parent.prototype creates unexpected behavior.

This assignment sets the proto property of Child.prototype to Parent.prototype. This means that any changes made to either Child.prototype or Parent.prototype will affect the other object's prototype. This behavior is problematic because it breaks the encapsulation and independence of separate object hierarchies.

In the example provided, assigning this.hitBox.width and this.hitBox.height in the Spaceship constructor leads to a different result depending on the inheritance method. When using Spaceship.prototype = new GameObject();, the this.proto property of Spaceship is set to GameObject, while when using Spaceship.prototype = GameObject.prototype, this.proto is set to Spaceship.

Instead of these methods, using Spaceship.prototype = Object.create(GameObject.prototype); creates a copy of the GameObject prototype, allowing for changes to Spaceship.prototype without affecting GameObject.prototype. This maintains the independence and encapsulation of object hierarchies while preserving the desired inheritance relationship.

The above is the detailed content of Why is Child.prototype = Parent.prototype a Bad Idea for JavaScript Inheritance?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn