Prototype Inheritance

Vaishnavi Neema
2 min readAug 10, 2023

--

Mostly Asked Interview Questions in Javascript

Functions are objects which have his own properties.

for eg: function foo {console.log(‘hello world!’)}

Now here if we check type of the function using typeof an operator
for eg: typeof foo.prototype // type is object

So, any time you create a function it will automatically have a property called as prototype which will be initiated as an empty object {}.

function Animal(name){
this.name = name;
}
Animal.prototype.sayHello = function(){
console.log(`hello I am ${this.name}`)
}
const cat = new Animal(‘cat’);
const dog = new Animal(‘dog’);
cat.sayHello();
dog.sayHello();
cat.hasOwnProperty(‘name’); // true
dog.hasOwnProperty(‘sayHello’); //false

OUTPUT:

hello I am cat
hello I am dog

Here’s how prototypal inheritance works in JavaScript:

Prototype Chain: Each object in JavaScript has a hidden property called [[Prototype]], which points to another object. When you access a property or method on an object, and the object itself doesn’t have that property, JavaScript looks up the prototype chain until it finds the property or reaches the end of the chain.

Constructor Functions: In JavaScript, constructor functions are used to create objects with shared properties and methods. These functions act as templates for creating new objects. By convention, constructor function names start with a capital letter.

Prototypes: Constructor functions have a property called prototype, which is an object that serves as the prototype for objects created using that constructor. Properties and methods added to the prototype are shared by all instances created from the constructor.

Instance Objects: When you create an instance using a constructor function with the new keyword, the [[Prototype]] of the instance points to the prototype object of the constructor.

To find the [[Prototype]] of an object, we will use the Object.getPrototypeOf() method.

--

--

Vaishnavi Neema
Vaishnavi Neema

Written by Vaishnavi Neema

Software Engineer, Learn Grow Earn Eat Repeat :)

No responses yet