Why Use the 'new' Keyword in Derived.prototype = new Base?
In JavaScript, inheritance is achieved through prototypes. To extend an existing class, you can assign the prototype of the child class to a new instance of the parent class. This is where the 'new' keyword comes into play.
In the following code:
WeatherWidget.prototype = new Widget;
The 'new' keyword serves two purposes:
What Happens if 'new' is Left Out?
Without 'new', you would not be calling the Widget constructor. Instead, you would need to provide an argument list for Widget(). However, this may not be possible and could lead to errors.
Importance of Not Sharing Properties
By default, instances of WeatherWidget would share property values from the same instance of Widget. This can lead to unexpected behavior, as multiple instances of WeatherWidget may override or modify each other's properties.
To prevent this, it's recommended to use a "Dummy" constructor (e.g., Dummy.prototype = Widget.prototype) as an intermediate step, which creates a new prototype for WeatherWidget that does not inherit property values from the parent instance. This ensures that each WeatherWidget instance has its own set of inherited properties.
Alternative Approaches in Newer JavaScript Versions
In ECMAScript 5 and later, you can use:
WeatherWidget.prototype = Object.create(Widget.prototype, { constructor: {value: WeatherWidget} });
This approach has the added benefit of making the constructor property non-writable, enumerable, or configurable.
Explicit Invocation of Parent Constructor
You may need to explicitly call the parent constructor (e.g., Widget.apply(this, arguments)) in the child constructor to initialize the parent instance.
Conclusion
Understanding the use of 'new' in Derived.prototype = new Base is crucial for implementing inheritance correctly in JavaScript. It ensures that child classes inherit from the correct prototype and prevents unintended sharing of property values between instances.
The above is the detailed content of Why Use `new` in `Derived.prototype = new Base` for JavaScript Inheritance?. For more information, please follow other related articles on the PHP Chinese website!