Javascript: prototype
The prototype is a property of any javascript function which is a point to an object.
# Let’s start with a very basic example
function Student() {
this.name = 'Harry';
this.gender = 'Potter';
}var studObj1 = new Student();
stdObj1.age = 15;
console.log(stdObj1.age);
// 15var stdObj2 = new Student();
console.log(stdObj2.age);
// undefined
As you can see in the above example, the age property is attached to the stdObj1 instance. However, the stdObj2 instance will not have age property because it is defined only on the studObj1 instance. So what to do if we want to add new properties at a later stage to a function that will be shared across all the instances? The answer is Prototype.
function Student() {
this.name = 'Harry';
this.gender = 'Potter';
}Student.prototype.age = 15;var studObj1 = new Student();
console.log(studObj1.age);
// 15var studObj2 = new Student();
console.log(studObj2.age);
// 15
# As you can see in the above example, Function’s prototype property can be accessed using <function-name>.prototype. However, an object (instance) does not expose prototype property, instead you can access it using __proto__
function Student() {
this.name = 'Tom';
this.gender = 'Cruise';
}var studObj = new Student();console.log(Student.prototype);
// [object Object]
console.log(studObj.prototype);
// undefined
console.log(studObj.__proto__);
// [object Object]console.log(typeof Student.prototype);
// object
console.log(typeof studObj.__proto__);
// object
### Changing Prototype
each object’s prototype is linked to the function’s prototype object. If you change the function’s prototype then only new objects will be linked to the changed prototype. All other existing objects will still link to the old prototype of the function. The following example demonstrates this scenario.
function Student() {
this.name = 'Tom';
this.gender = 'Male';
}Student.prototype.age = 15;var studObj1 = new Student();
console.log('studObj1.age = ' + studObj1.age);
// 15var studObj2 = new Student();
console.log('studObj2.age = ' + studObj2.age);
// 15Student.prototype = { age: 20 };var studObj3 = new Student();
console.log('studObj3.age = ' + studObj3.age);
// 20console.log('studObj1.age = ' + studObj1.age);
// 15
console.log('studObj2.age = ' + studObj2.age);
// 15
### Use of Prototype
The prototype object is being used by the JavaScript engine in two things, 1) to find properties and methods of an object 2) to implement inheritance in JavaScript.
function Student() {
this.name = 'Robert';
this.gender = 'Pattinson';
}Student.prototype.sayHi = function () {
console.log("Hi");
};var studObj = new Student();
studObj.sayHi();
// Hi
### Share method by using a prototype
function Person(name, age){
name = name;
age= age;
}Person.prototype = {
eat(){
console.log('Person is eating');
},
sleep(){
console.log('Person is sleeping');
},
play(){
console.log('Person is playing');
}
}const harry = new Person("Harry", 36);harry.eat();
//Person is eating