Understanding Object Prototyping in JavaScript: Exploring the Prototype Chain
In JavaScript, object prototyping is a fundamental concept that allows objects to inherit properties and methods from other objects. This powerful mechanism is known as the prototype chain. In this blog post, we will explore the concept of object prototyping using a practical example. We'll dive into the given code snippet and understand how objects in JavaScript can inherit and share functionality through prototypal inheritance.
const car = {
wheels: 4,
emoji: '🚗',
start () {
return('vroom!!');
}
};
const camry = {
doors: 4,
maker: 'Toyota'
};
const camry_v4 = {
engine: 2.5
};
const camry_v6 = {
engine: 3.5
};
// The `Object.setPrototypeOf()` function is used to change the prototype of an object.
// The prototype of an object is the object that is used to inherit properties from.
// By default, the prototype of a new object is the `Object.prototype` object.
// However, the `Object.setPrototypeOf()` function can be used to change the prototype to any other object.
Object.setPrototypeOf(camry, car);
// This means that the `camry` object will inherit the properties of the `car` object,
// including the `wheels`, `emoji`, and `start()` properties.
console.log(camry, camry.start());
// The output of the `console.log()` function shows that the `camry` object has the properties of the `car` object.
console.log(Object.getPrototypeOf(camry));
// The output of the `console.log()` function shows that the prototype of the `camry` object is the `car` object.
Object.setPrototypeOf(camry_v4, camry);
// This means that the `camry_v4` object will inherit the properties of the `camry` object,
// including the `doors`, `maker`, `engine`, and `start()` properties.
const camry_VIN_123 = {
color: 'red',
year: '2020',
};
Object.setPrototypeOf(camry_VIN_123, camry_v4);
// This means that the `camry_VIN_123` object will inherit the properties of the `camry_v4` object,
// including the `engine` property.
console.log(
camry_VIN_123,
camry_VIN_123.doors,
camry_VIN_123.emoji,
camry_VIN_123.engine,
camry_VIN_123.start()
);
// The output of the `console.log()` function shows that the `camry_VIN_123` object
// inherits the properties of the `camry_v4` object.