Home > Article > Web Front-end > When to Choose Object.create Over new for JavaScript Inheritance?
JavaScript Inheritance: Object.create vs. new
The concept of inheritance in JavaScript can be confusing, as there are various approaches to achieving it. This article aims to clarify the most accepted methods and provide a solution for your specific scenario.
Understanding Object.create and new
Object.create is a method that creates a new object by inheriting from an existing object. This is useful when you want to create a base object and then extend it with additional properties and methods. The syntax for Object.create is:
Object.create(prototype[, propertiesObject])
On the other hand, the new keyword is used to create a new instance of an object and invoke its constructor function. The syntax for new is:
new ConstructorFunction([arguments])
Choosing the Right Method for Inheritance
The choice between Object.create and new depends on your specific requirements. Object.create is ideal for creating base objects that you want to inherit from without invoking their constructors. For example:
const Model = { // Base object properties and methods... }; const RestModel = Object.create(Model);
If, however, you want to call the constructor function of the base object on the inheriting object, then you should use new. For example:
function Model() { // Base object constructor... } function RestModel() { Model.call(this); // Additional properties and methods... }
Solution for Your Scenario
In your case, you want to inherit the RestModel from the Model base object. To achieve this using Object.create, you would do the following:
RestModel.prototype = Object.create(Model.prototype);
This will create a new RestModel prototype that inherits from the Model prototype.
The above is the detailed content of When to Choose Object.create Over new for JavaScript Inheritance?. For more information, please follow other related articles on the PHP Chinese website!