Prototypes methods & features in javascript

In this tutorial we'll learn about prototypes in javascript and their methods and features in depth with examples

In JavaScript, objects have a special hidden property known as Prototype which depicts either null or references another object. Now, that object is called a prototype. In this advanced JavaScript Tutorial, we will discuss two important features of prototype

  1. Prototypal Inheritance
  2. Prototype methods

🔗Prototypal Inheritance

When we read a property from object, and if it's missing javascript automatically takes it from the prototype this is called Prototypal Inheritance

Let's learn Prototypal Inheritance with a one simple example for better understanding

Let’s see we have a two different object codingbatch and codingsumit where first object contains programmer property and second contains developer property

js
let codingsumit = { programmer: "learn programming " };
let codingbatch = { developer: "learn web dev" };

lets set codingbatch object to codingsumit object by using proto in programming this is called Prototypal inheritance

js
codingbatch.__proto__ = codingsumit; // sets codingbatch to codingsumit.

Now if we read a property from codingbatch, and if property missing, JavaScript will automatically take it from codingsumit.

we can find both properties developerand programmer in codingbatch now:

js
console.log(codingbatch.programmer); // learn programming
console.log(codingbatch.developer); // learn web dev
Prototypal Inheritance

🔗Prototypal method

The __proto__ is considered outdated and somewhat deprecated (in browser only part of the JavaScript standard).

The modern methods are:

  • Object.create(proto, [descriptors])
  • Object.getPrototypeOf(obj)
  • Object.setPrototypeOf(obj, proto)

  1. Object.create(proto, [descriptors]) :- creates an empty object with given proto as [[Prototype]] and optional property descriptors.
js
let codingbatch = { programmer: "learn programming" };
// create a new object with codingbatch as a prototype
let codingsumit = Object.create(codingbatch);
console.log(codingsumit.programmer); // learn programming
ProtoObject.create(proto, [descriptors])
  1. Object.getPrototypeOf(obj) : – returns the [[Prototype]] of obj.
js
let codingbatch = { programmer: "learn programming" };
let codingsumit = Object.create(codingbatch);
console.log(Object.getPrototypeOf(codingsumit));
Object.getPrototypeOf(obj)
  1. Object.setPrototypeOf(obj, proto) : – sets the [[Prototype]] of obj to proto.
js
let codingbatch = { programmer: "learn programming" };
let codingsumit = Object.create(codingbatch);
Object.setPrototypeOf(codingsumit, {
programmer: "javascript programming",
});
console.log(codingsumit.programmer);