Prototypes in JavaScript

📄 Table of Contents

Problem with creating objects with the “constructor” function

var person1 = new Human("Virat", "Kohli");
var person2 = new Human("Sachin", "Tendulkar");

Prototypes

console.log(person1);
console.log(Human.prototype)

Creating an object using the constructor function

Human.prototype === person1.__proto__ (# true)
//Create an object person1 using the Human constructor function
var person1 = new Human("Virat", "Kohli");
Human.prototype === person1.__proto__ //true
var person2 = new Human("Sachin", "Tendulkar");
console.log(person2);
Human.prototype   === person2.__proto__      //true
person1.__proto__ === person2.__proto__ //true

How to define a property on the prototype of the Array object

var last = arr.last;
Object.defineProperty(Array.prototype, ’last’ ,{get: function()
{return this[this.length-1];}});
var arr1=[4,5,6];arr1.last; // This would give me 6.

Prototype Object

console.log(person1);
var person2 = new Person();//Access the name property using the person2 object
console.log(person2.name)// Output: Ashwin
person1.name = "Anil"
console.log(person1.name)//Output: Anil
console.log(person2.name)//Output: Ashwin

◉ Problems with the prototype

Consider another example to display the issue with prototypes when the prototype object contains a property of reference type

◉ Combine Constructor/Prototype to overcome above problem

Question

const jamesBond = {
firstName: "Daniel",
lastName: "Craig",
getFullName: function () {
return `${this.firstName} ${this.lastName}`.trim();
}
};
jamesBond.getFullName();
Object.prototype.getFullName = function () {
return `${this.firstName} ${this.lastName}`.trim();
};
const jamesBond = {
firstName: "Daniel",
lastName: "Craig"
};
jamesBond.getFullName();

Solution

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.

Get the Medium app