# Javascript Prototype

# What is a prototype

As you already know, every function has a prototype property, which contains an object. When this function is invoked using the new operator, an object is created and this object has a secret link to the prototype object. The secret link (called proto in some environments) allows methods and properties of the prototype object to be used as if they belong to the newly-created object.

Prototype is a core concept in JavaScript and an important mechanism in implementing the OOP pattern in JavaScript. All objects in javascript have a prototype, and these objects inherit properties and methods from their prototype.

In JavaScript, except undefined, all other types are objects. String, number, and boolean types are objects in the form of String, Number, and Boolean, respectively. An array is an Array object, a function is a Function object. The prototype of each object is its parent, String's parent is String.prototype, Number's parent is Number.prototype, and Array's is Array.prototype.

You should notice🧐 that the prototype itself is an object in JS, called the prototype object. We need to know this to avoid confusion with the function's prototype property.

## Function prototype

In JavaScript, all functions are also objects, which means that they can have properties. And it happens that they all have a property called prototype in common, whose type is also an object.

```
function doSomething() {
}
console.log(typeof doSomething.prototype); // ‘object’
```

 ## understanding of prototype chain

1. Prototypes are very important in giving us access to an object's properties and methods. The object's prototype property (also known as the prototype object) is a "parent object" where the properties and methods are inherited.

2. So, when we call an object's property (eg: student1.age), Js will initially look in the object's own property, if not found, it will continue to look in the object's prototype, and iterate with the prototype of the prototype object, etc.

This iterative process is called prototype chaining in Javascript. It is this + the function's prototype property that makes up the prototype-based inheritance mechanism for Javascript.

```
var obj1 = { a: 1 };
var obj2 = Object.create(obj1);
obj2.b = 2;
console.log(obj1.a); // first
console.log(obj2.a); // first
console.log(obj2.b); // 2
console.log(obj2.c); // undefined
```
In the above example, Object.create() will create a new object obj2 with prototype obj1. And as we have seen, even though obj2 doesn't have a property a, we can still access it thanks to the prototype chain mechanism.
