JavaScript Inheritance: Unveiling the Defacto Standard
Despite numerous articles delving into JavaScript inheritance, confusion often arises due to the plethora of available approaches. To clarify this enigmatic subject, we explore the most accepted methods and provide tailored guidance for your specific scenario.
Choosing the Appropriate Inheritance Mechanism
Understanding the distinction between new and Object.create is crucial for selecting the optimal inheritance strategy. While both techniques facilitate object creation, they serve different purposes. Object.create generates a new object that inherits from another, whereas new additionally invokes a constructor function.
Applying to Your Use Case
Your objective is to establish a base object named Model with extendible subclasses RestModel and LocalStorageModel. In this scenario, Object.create emerges as the preferred method. This approach aligns with your intention to create a prototype inheritance hierarchy without invoking the Model constructor.
<br>RestModel.prototype = Object.create(Model.prototype);<br>
Invoking a Constructor in Subclasses
If invoking the Model constructor for RestModels is desired, this is not accomplished through inheritance. Instead, call() or apply() provide the means to trigger constructor execution.
<br>function RestModel() {</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">Model.call(this); // Apply Model's constructor on the new object ...
}
By comprehending these concepts, you can confidently implement inheritance in JavaScript, empowering your applications with the flexibility and extensibility they require.
The above is the detailed content of JavaScript Inheritance: Object.create vs. new: Which is Right for You?. For more information, please follow other related articles on the PHP Chinese website!