Web DesignFrontend

What is Prototype in Js?

All objects inherits property and methods from prototype. I think you already know what is object Right?

May be you don’t know, function is also a object. check prototype of function .

Suppose you are declaring a constructor and you want to declare a property which can be access by different instance then you have to declare prototype.

lets create a constructor function not constructor class:

function Circle(r){
  this.radius = r;
}
const createCircle =  new Circle(12);
console.log(createCircle.radius);

If you try to access any property of constructor, you have to use new keyword and also you have to use first word capital.

You have to use this keyword in constructor for property and methods.

Every object and function has __proto__ property that points to prototype of object or function.

Object’s Prototype

Try to console.log() any object or empty object, you will see it has __proto__  in console.log.

Let’s declare and initialize a empty object:

const myobject ={}

After that try to console.log it.

you will see too many method which is use to perform may action like toString(), hasOwnProperty,.

Setting a Prototype By Two ways:

There are two ways to setting up a prototype:

  1. Object.create()

Object.create() is use to create a new object which will create new object prototype.

const person = {
  greet() {
    console.log('connect digital!');
  }
}

const carl = Object.create(person);
carl.greet();  // connect digital!

2. Constructor

const personPrototype = {
  greet() {
    console.log(`hello, my name is ${this.name}!`);
  }
}

function Person(name) {
  this.name = name;
}

Person.prototype.greet = personPrototype.greet;
const reuben = new Person('Reuben');
reuben.greet(); // hello, my name is Reuben!

 

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button