Skip to main content

Command Palette

Search for a command to run...

Javascript Object ,Prototype and Prototype chaining

Published
2 min readView as Markdown
Javascript Object ,Prototype and Prototype chaining
A

Hey There, I am going to start my new blogging journey, as I am learning full stack web development and I will sharing my all learning here. Keep learning Keep Growing :)

What is an Object?

Objects in JavaScript are also dynamic, it can also have properties and methods added or removed at runtime. Each object has a unique identity and it is an instance of an object constructor

//Creating the Object
const object ={
    car:"TATA-Nexon",
    bike:"Activa",   
}
console.log(object)

//OUTPUT :- { car: 'TATA-Nexon', bike: 'Activa' }
//Creating Object as a constructor
const object1 = new Object()
object1.fule=200
object1.car="Tata Safari Wagenor Swift"
console.log(object1)
// OUTPUT :-{ fule: 200, car: 'Tata Safari Wagenor Swift' }

What is Prototype?

In JavaScript, a prototype is an object that serves as a template for creating new objects. When a new object is created, it inherits properties and methods from its prototype. The prototype of an object can be accessed using the Object.getPrototypeOf() method and can be modified using the Object.setPrototypeof() method or the proto property. The built-in Object constructor has a property called prototype.

//Define Function
function Person(name,age){
    this.name=name; 
    this.age=age;
}
//define prototype and creaating the function
Person.prototype.data = function() {
    console.log("my name is " + this.name);
    console.log("my Age is " + this.age);
};
//define new object and callding data object function
let person1=new Person("Ashutosh",24)

console.log(person1.data());
console.log(person1.age());

//OUTPUT :-my name is Ashutosh my age is 24

Prototype chaining

Prototype chaining is the mechanism in the javascript that was used to inherit the properties of one object to another object. By using prototype changing we can also get access to parent object methods in the current object.

For inheriting the properties of another method in our object we can use the __Proto__ keyword.

Syntax

__Proto__ : test1

__Proto__--This is the keyword that can be used to access the method of the object.

test1--it defines the object name from where we can access those methods.

Example

//Creating the Object
let test1={
    username:"ashutosh",
    password:"Ashu@123"
}
//creating 2 nd object
let test2={
//calling methos from test1 using proto
    __proto__:test1,
}
console.log("username is "+test2.username);
console.log("Password is "+test2.password);

//OUTPUT:-username is ashutosh
//OUTPUT:-Password is Ashu@123