class Student{
//initialising an object
constructor(roll,name){
this.roll=roll;
this.name=name;
}
//method
display(){
console.log(this.roll," -> ",this.name);
}
}
let s1=new Student(101,"Ravi");
s1.display();
let s2=new Student(102,"Raj");
s2.display();
Common property of all the objects of a common class.
To add properties to class after creation of object of class.
let std1=new Student(101,"Ravi");
let std2=new Student(102,"Raj");
Student.prototype.clg="PVP";
console.log(std1);
console.log(std2);
console.log(std1.__proto__);
console.log(std1.toString());
We can create a base object with generic props that can be used in other objects, the use prototype concept to inherit those props to child objects.
We can use static method *Object.setPrototypeOf( childName, baseName );*
let stud={
college:"PVP",
city:"Vijayawa
da",
ph:1234567890,
display:function(){
console.log(this.college," -> ",this.city," -> ",this.ph);
}
}
let st1={
name:"Ravi",
age:21
};
let st2={
name:"Raj",
age:22
};
Object.setPrototypeOf(st1,stud);
Object.setPrototypeOf(st2,stud);
console.log(st1);
// class inheritance
class Parent{
college="PVP";
city="Vijayawada";
ph=1234567890;
}
class Child extends Parent{
name="Pavan";
age=18;
}
let c=new Child();
console.log(c);
//prototype inheritance
function Parent1(){
this.college="PVP";
this.city="Vijayawada";
this.ph=1234567890;
}
function Child1(){
this.name="Pavan";
this.age=18;
}
Child1.prototype=new Parent1();
let c1=new Child1();
console.log(c1);