Home >Web Front-end >JS Tutorial >Why Does `Child.prototype = Parent.prototype` Break JavaScript Inheritance?

Why Does `Child.prototype = Parent.prototype` Break JavaScript Inheritance?

Barbara Streisand
Barbara StreisandOriginal
2024-11-19 00:55:02353browse

Why Does `Child.prototype = Parent.prototype` Break JavaScript Inheritance?

Why Child.prototype = Parent.Prototype Might Break Javascript Inheritance?

In Javascript inheritance, you may have encountered the following pattern for inheritance:

function GameObject(oImg, x, y) {
    // GameObject constructor
}

Spaceship.prototype = new GameObject();
Spaceship.prototype.constructor = Spaceship;

However, you may have noticed an unexpected behavior when adding properties to Spaceship.prototype after inheritance. The prototype property of Spaceship gets set to Spaceship rather than GameObject.

This occurs because when you set Spaceship.prototype = GameObject.prototype, the two prototypes start referring to the same object. Any modification to one object will affect the other. Therefore, adding properties to Spaceship.prototype will also add them to GameObject.prototype.

To avoid this issue, you can use:

Spaceship.prototype = Object.create(GameObject.prototype);

This creates a new object with GameObject.prototype as its prototype, ensuring that modifications to Spaceship.prototype won't affect GameObject.prototype.

Alternatively, if you want to invoke the constructor, use GameObject.apply(this, arguments) within the Spaceship constructor instead of the above line.

The above is the detailed content of Why Does `Child.prototype = Parent.prototype` Break 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