Prototype - The Backbone of JavaScript

Prototype - The Backbone of JavaScript

·

6 min read

All JavaScript types are based internally on objects called prototypes, including Javascript arrays and strings.

The JavaScript standerd describe Prototype describe how Javascript ES6 clesses work internally and have been an important part of Javascript for decades.

Objects :

There are various ways to create objects in JavaScript…

1. JavaScript Objects

There are various ways to create objects in JavaScript..

1. Object Initializers (Object Literals)

Object initializers, also known as object literals, are a concise way to create objects. To define an object using an object initializer, we use curly braces and define properties with their respective values.

const person = {
  name: "Hitesh @ Piyush",
  age: 28
  gender: "male",
};

2. Constructor Functions and the "new" Operator

Constructor functions are used to create multiple instances of objects with similar properties and behaviors. The function acts as a blueprint for the object, and the "new" operator is used to create instances.

function Person(name, age, gender) { //Ek simple function create Kiya
  this.name = name;
  this.age = age;
  this.gender = gender; // Isme this. Keyword function ko define kiya
}

const person1 = new Person("Hitesh sir", 30, "male"); // for new:- iske liye new mwmory create kiya 
const person2 = new Person("Priya mam", 28, "female");

3. Using the Object.create() Method

The Object.create() method allows us to create new objects with a specified prototype object. This method is useful when we want to create an object based on an existing prototype without using constructor functions.

const King = {   // Create object
  type: "Invertebrates", // define a type 
  displayType() {
    console.log(this.type);
  },
};

const King1= Object.create(king);
King1.displayType();

const sir= Object.create(king);
sir.type = "sir";
sir.displayType();

Prototypes in Built-in Types

Array and string methods for complex object manipulations are part of their object prototypes. For example, the array method valueOf() and the string method subString() are both prototype methods accessible directly through their object or through its prototype.

let source = [1, 2, 3];  // Array Prototype...
let = sourceData.values();
for (const value of sourceData) {
    console.log(value);
}

let source1= "My String";  // String Prototype...
let sourceData1= String.prototype.substring(source1, 0, 2);

Understanding Prototypes in JavaScript :

Prototype: Hm sbhi jaante hai ki “Proto“ ka mins jiske liye jo protocol bnaya gya hai phle se, aur “Type“ Us protocol ko follow krne ke liye jo rule bnaya gya us type ko hi Prototype khte hai.

The Array object has a prototype Array.prototype and the object instance, num, inherits the properties of the Array object.

This is why you can use a method like sort() on an array instance.


console.log(numArray.sort()); // -> [-4, -8, 1, 2, 3, 7]

When a constructor (a.k.a. pseudo classical inheritance) function is built, the newly created objects inherit the prototype properties of the constructor function and that’s the critical feature of constructors. They (constructor functions) are built for the initialization of newly created objects. Constructors are invoked using the new keyword.

const Car = function(color, model, dateManufactured) {
this.color = color;
this.model = model;
this.dateManufactured = dateManufactured;
};

Car.prototype.getColor = function() {
return this.color;
};

Car.prototype.getModel = function() {
return this.model;
};

Car.prototype.carDate = function() {
return `This ${this.model} was manufactured in the year ${this.dateManufactured}`
}

let firstCar = new Car('red', 'Ferrari', '1985');
console.log(firstCar);
console.log(firstCar.carDate());

From example.. above, the carDate, getColor and getModel functions are properties of the Car object and instances of the Car object like firstCar can inherit all its properties.

The Prototype Chain - How Inheritance Works:

When an object gets a request for a property, that it does not have, its prototype will be searched for the property, then the prototype’s prototype, and so on.

So who is the prototype of an object ……..,

It is the great ancestral prototype, the entity behind almost all objects, Object.prototype. Many objects don’t directly have Object.prototype as their prototype, but instead have another object that provides a different set of default properties. Functions derive from Function.prototype, and arrays derive from Array.prototype and so on.

let protoRabbit = {
color: 'grey',
speak(line) {
console.log(`The ${this.type} rabbit says ${line}`);
  }
};

let typeRabbit = Object.create(protoRabbit);
typeRabbit.type = "assassin";
typeRabbit.speak("Seemes!");

ProtoRabbit - acts as a container that is shared by all Rabbits. Rabbit An object, such as TypeRabbit, that only applies to it - in this case its type - and inherits shared properties from its prototype.

Prototype chain, lookup process, if you use a for..in loop to iterate over an object, any property that can be reached via its chain and is also enumerable will be enumerated. If you use the in operator to test for the existence of a property on an object, it will check the entire chain of the object. (it min’s ki numerial value ki bina calculation bina kisi ka prwah kiye krna….! )

let protoRabbit = {
color: 'grey',
speak(line) {
console.log(`The ${this.type} rabbit says ${line}`);
}
};

let tupeRabbit = Object.create(protoRabbit);
typeRabbit.type = "assassin";
typeRabbit.speak("SKREEEE!");

The code above is in efficient because if you were to create multiple rabbit objects, you would have the same function written everywhere and that’s where prototype and constructor functions really come in.

It can be re written like this:

let protoRabbit = function(color, word, type) {
this.color = color;
this.word = word;
this.type = type;
};

protoRabbit.prototype.getColor = function() {
return this.color;
}

protoRabbit.prototype.speak = function() {
console.log(`The ${this.type} rabbit says ${this.word}`);
}

let killerRabbit = new protoRabbit('grey', 'Seemes', 'assign');
killerRabbit.speak();

:Tree structure of prototype Model work:

Modifying Prototypes - Do's and Don'ts :

Prototype that refine the design further based on feedback of the prototype. They are tweaks and refinements to specific parts of the design which can be updated and altered without affecting the rest of the assembly. As a result, the modifications can be reassembled back into the existing prototype reducing the need to remake the rest of the assembly. There are two different types of modifications:

1. modify the parts themselves such as filing down the inside of a print, so it fits inside another part with less resistance.
2. redesigning parts and remaking them based on the new design and building these back into the assembly.

The modification may only consist of one type of modification or if there are multiple modifications in the scope of work then the stage may contain both.

The prototyping project actively involves visitors in the development process; prototypes are used at different stages of the project; efficiency is improved with the help of prototyping tools; spectacular prototyping failures are learned from; prototyping is used for other purposes. And in small groups, complete prototyping tasks (with real prototypes!). We will conclude the session with a discussion aimed at creating a shared list of do's, don'ts, and best practices in prototyping.