Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
In JavaScript inheritance how to differentiate Object.create vs new?
In JavaScript inheritance, Object.create() and new serve different purposes when setting up prototype chains. Understanding their differences is crucial for proper inheritance implementation.
Object.create() - Prototype Only Inheritance
When using Object.create(), you inherit only the prototype methods without executing the parent constructor:
function BaseClass(name) {
this.name = name;
console.log("BaseClass constructor called");
}
BaseClass.prototype.greet = function() {
return "Hello from " + this.name;
};
function ChildClass(name) {
this.name = name;
}
// Using Object.create - inherits prototype only
ChildClass.prototype = Object.create(BaseClass.prototype);
ChildClass.prototype.constructor = ChildClass;
let child = new ChildClass("Alice");
console.log(child.greet());
Hello from Alice
new Operator - Full Object Inheritance
Using new creates an instance and executes the parent constructor, inheriting both properties and methods:
function BaseClass(name) {
this.name = name;
console.log("BaseClass constructor called");
}
BaseClass.prototype.greet = function() {
return "Hello from " + this.name;
};
function ChildClass(name) {
this.name = name;
}
// Using new - executes constructor and inherits everything
ChildClass.prototype = new BaseClass("Default");
ChildClass.prototype.constructor = ChildClass;
let child = new ChildClass("Bob");
console.log(child.greet());
BaseClass constructor called Hello from Bob
Key Differences
| Aspect | Object.create() | new Operator |
|---|---|---|
| Constructor Execution | No | Yes |
| Inherits Properties | No | Yes |
| Inherits Methods | Yes | Yes |
| Performance | Better | Slower |
| Recommended | Yes | No |
Why Object.create() is Preferred
Object.create() is the modern approach because it avoids unnecessary constructor calls and potential side effects:
function Animal(species) {
this.species = species;
this.alive = true;
}
Animal.prototype.makeSound = function() {
return "Some sound";
};
function Dog(name, breed) {
Animal.call(this, "Canine"); // Proper constructor call
this.name = name;
this.breed = breed;
}
// Correct inheritance setup
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
return "Woof!";
};
let myDog = new Dog("Rex", "German Shepherd");
console.log(myDog.species);
console.log(myDog.makeSound());
console.log(myDog.bark());
Canine Some sound Woof!
Conclusion
Use Object.create() for clean prototype inheritance without executing parent constructors. The new approach is outdated and can cause issues with unwanted constructor side effects.
