Difference Between Objects and Prototypes in JavaScript
Last Updated :
11 Dec, 2023
Objects in JavaScript
The Objects in JavaScript are instances of the class or constructors and they can hold properties and methods. These properties and methods can be unique to the object or inherited from the prototypes. The Objects can be created using the constructor functions, object literals, or Object constructors.
Syntax:
const person = {
name: 'Kumar',
age: 20,
greet: function() {
// code
}
};
Example: In this Example, a car object might have properties like “make” and “model” and methods for starting the engine or changing gears.
Javascript
car1 = { make: 'Toyota' , model: 'Camry' };
car1.start = function () {
console.log( 'Engine started' );
};
car1.start();
|
Prototypes in JavaScript
The Prototypes in JavaScript are template objects that provide shared properties and methods to the other objects. Every object has a built-in property that is called its prototype. and prototype is an object itself so it also has its own prototype. They are not created explicitly as prototypes but exist as a blueprint for the objects of the specific type. The Prototypes facilitate inheritance by allowing the objects to inherit their properties and methods.
Syntax:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
// code
}
Example: In this example, a Cars constructor function is defined to create car objects with make and model properties, and a shared start method is added to the Cars prototype for initiating the engine.
Javascript
function Cars(make, model) {
this .make = make;
this .model = model;
}
Cars.prototype.start = function () {
console.log( 'Engine started' );
};
const myCars = new Cars( 'Toyota' , 'Camry' );
const anotherCars = new Cars( 'TATA' , 'Accord' );
myCars.start();
anotherCars.start();
|
Output
Engine started
Engine started
Difference Between Objects and Prototypes in JavaScript
The Objects are instances of the classes or constructors and they can hold properties and methods.
|
The Prototypes are template objects that provide the shared properties and methods to other objects.
|
Created using the constructor functions, object literals or Object constructor.
|
Not created explicitly as prototypes but exist as a blueprint for the objects.
|
The Objects have their own unique properties and can inherit from the prototypes.
|
The Prototypes define shared properties that can be inherited by the objects.
|
The Objects can have their own methods, distinct from the methods in the prototypes.
|
Prototypes can define methods that are shared the among objects of same type.
|
The Objects can inherit from the other objects using the mechanisms like Object.create() or constructors.
|
Prototypes facilitate inheritance by allowing the objects to inherit their properties and methods.
|
Share your thoughts in the comments
Please Login to comment...