Home > Web Front-end > JS Tutorial > How Does the `new` Keyword Impact Prototype-Based Inheritance in JavaScript?

How Does the `new` Keyword Impact Prototype-Based Inheritance in JavaScript?

Barbara Streisand
Release: 2024-12-14 15:34:22
Original
878 people have browsed it

How Does the `new` Keyword Impact Prototype-Based Inheritance in JavaScript?

Prototype-Based Inheritance: Delving into the 'new' Keyword's Role

When extending a Widget class with a new function named WeatherWidget, the prototype assignment:

WeatherWidget.prototype = new Widget;
Copy after login

plays a crucial role. The 'new' keyword invokes the Widget constructor and assigns its return value to the prototype property of WeatherWidget.

If omitted, this action would raise an error or possibly pollute the global namespace. By using 'new', the Widget constructor is invoked, ensuring proper initialization and a valid return value.

However, this approach creates a scenario where all WeatherWidget instances inherit properties from the same Widget instance, sharing values among themselves. This may not align with inheritance principles.

To rectify this issue and implement true class-based inheritance, the following steps should be taken:

  1. Create a Dummy Object:
function Dummy () {}
Dummy.prototype = Widget.prototype;
Copy after login
  1. Assign the Prototype:
WeatherWidget.prototype = new Dummy();
Copy after login
  1. Fix the Constructor:
WeatherWidget.prototype.constructor = WeatherWidget;
Copy after login

This approach ensures that WeatherWidget instances inherit properties through the prototype chain without sharing values among themselves.

For a more concise solution in ECMAScript Ed. 5 and later, consider using:

WeatherWidget.prototype = Object.create(Widget.prototype, {
  constructor: {value: WeatherWidget}
});
Copy after login

Alternatively, for a generalized inheritance implementation, explore Function.prototype.extend(). This method enables easy prototype augmentation and provides a convenient 'super' access function for invoking parent methods.

The above is the detailed content of How Does the `new` Keyword Impact Prototype-Based Inheritance in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template