One may have often heard that JavaScript is a prototype-based language, or you may have heard about it but not really understood.
Prototype is a concept in JavaScript that describes how objects share data or methods from other objects through a chain of inheritance.
Example: A child’s prototype is his biological mother and father. This means that, by default, the child inherits some properties(data) from the parent.
So, if the child is asked what country they are from, they already have that prototype from their parent. i.e., child.country
.
When an object property is not known in JavaScript, the JavaScript engine goes through the prototype chain to find the
Object.create()
)//Should be a prototype of other sportsconst sports = {isBeautiful: true,language: "love",}const football = Object.create(sports);// Check the prototype of football and sportsconsole.log(Object.getPrototypeOf(football));// Access one of the prototypesconsole.log(football.language)
Here, we created a literal object called sports, a prototype for the different kinds of sports we have. Then, we create a football object and use the Object.create()
.
.prototype
)function sports(){}// Every function has .protype propertysports.prototype.language = "love";sports.prototype.isBeautiful = true;const football = new sports();// Check the prototype of footballconsole.log(Object.getPrototypeOf(football));// Access one of the prototypesconsole.log(football.language)
Every function in JavaScript has the .prototype
property. With this, we can add as many prototypes as we want.
extends
)class GrandParent{laugh(){console.log("hahahaha");}}class Parent extends GrandParent{}const child = new Parent();// Check the prototype of Parent and childconsole.log(Object.getPrototypeOf(Parent))console.log(Object.getPrototypeOf(child))// Access one of the prototype properties of the childchild.laugh()
Here, we created a GrandParent
class and, using the extends
keyword, the Parent
class inherited its prototype. Lastly, the child
object inherits the prototype from the Parent
.
JavaScript is a prototype-based language. When a certain property of an object is not found, it will return undefined. This is because it will have found no such property across the prototype chain of the object. Moreover, there are numerous ways to create prototypal inheritance through functions, constructor functions, and class.