Home >Web Front-end >JS Tutorial >Object.create vs. new: When to Use Which for JavaScript Inheritance?
JavaScript Inheritance: Object.create vs. new
In JavaScript, inheritance can be achieved through various methods. Two commonly discussed approaches are using the new keyword and Object.create. When exploring inheritance, the sheer number of available options can be daunting.
To clarify the most accepted way of achieving inheritance in JavaScript, let's explore the differences between Object.create and new.
Object.create
Object.create is used to create a new object that inherits from another object. It does not invoke the constructor function of the parent object. This is useful when you only want to create a new object that inherits specific properties and methods from a parent object.
const baseModel = { property1: "value1", method1: function() {} }; const newModel = Object.create(baseModel);
In this example, newModel inherits the property1 and method1 from baseModel.
new
The new keyword calls the constructor function of a class or object and creates a new instance of that class or object. It invokes the constructor function and thus initializes the new object with specific properties and methods.
class BaseModel { constructor(property1) { this.property1 = property1; } method1() {} } const newModel = new BaseModel("value1");
In this example, newModel is an instance of the BaseModel class with the property1 initialized to "value1".
Choosing the Right Approach
The choice between Object.create and new depends on whether you need to create a new object that inherits properties and methods or invoke the constructor function of the parent object.
In the given scenario, you want to have a base object Model which you can extend with RestModel or LocalStorageModel. Using Object.create (or its shim) is the correct way because you do not want to create a new instance of Model and call its constructor.
RestModel.prototype = Object.create(Model.prototype);
If you want to call the Model constructor on RestModels, use call() or apply() instead:
function RestModel() { Model.call(this); // apply Model's constructor on the new object ... }
The above is the detailed content of Object.create vs. new: When to Use Which for JavaScript Inheritance?. For more information, please follow other related articles on the PHP Chinese website!