Consider the following code snippet:
WeatherWidget.prototype = new Widget;
where Widget represents a constructor, and our goal is to extend it with a new function called WeatherWidget. The question arises: what is the significance of the new keyword in this context, and what ramifications would arise if it were omitted?
The new keyword performs a crucial operation by instantiating Widget as a constructor and assigning its return value to the prototype property of WeatherWidget. If the new keyword was absent, calling Widget without providing argument(s) (e.g., by omitting the parentheses) would result in undefined behavior. Moreover, if Widget's implementation is not designed to be called as a constructor, this approach might inadvertently pollute the global namespace.
By using the new keyword as demonstrated, all instances of WeatherWidget will inherit from the same Widget instance, resulting in the following prototype chain:
[new WeatherWidget()] → [new Widget()] → [Widget.prototype] → …
This particular arrangement can be suitable when all WeatherWidget instances are intended to share property values inherited from the Widget instance. However, in most scenarios, such shared inheritance is undesirable.
To effectively implement class-based inheritance in JavaScript, which uses prototypes, the following approach is recommended:
function Dummy () {} Dummy.prototype = Widget.prototype; WeatherWidget.prototype = new Dummy(); WeatherWidget.prototype.constructor = WeatherWidget;
This technique ensures that WeatherWidget instances properly inherit properties through the prototype chain, but without sharing property values among instances because they inherit the prototype from the intermediary Dummy constructor. Here's the resulting prototype chain:
[new WeatherWidget()] → [new Dummy()] → [Widget.prototype] → …
In modern JavaScript implementations that adhere to ECMAScript 5 and later, the following approach is preferred:
WeatherWidget.prototype = Object.create(Widget.prototype, { constructor: {value: WeatherWidget} });
This approach has the added benefit of creating a non-enumerable, non-configurable constructor property.
Finally, it's important to note that the parent constructor (in this case, Widget) will only be called explicitly from within the child constructor (WeatherWidget), similar to how apply or call methods are used:
function WeatherWidget (…) { Widget.apply(this, arguments); }
The above is the detailed content of What is the Role of `new` in JavaScript Prototypal Inheritance: `Derived.prototype = new Base`?. For more information, please follow other related articles on the PHP Chinese website!