Prototype and Prototype chaining
Prototype : every object in javscript have built in property , which is called Prototype.
INHERITANCE in Javscript : is called PROTOTYPAL Inheritance .When you try to access property of object , property will not only be looked for in object but on the prototype of object and on the prototype of prototype and this goes on until matching property is found
Prototype chaining :
const myObject = {
city: "Akola",
greet() {
console.log(`Greetings from ${this.city}`);
},
};
myObject.greet(); // Greetings from Akola
this is an object (myObject) with one property(city) and one method greet(). If you type object name (myobject) on console . Then console will pop up all object properties of ( myobject ) , you will see that city and method greet() also have lots of properties
like that:
defineGetter defineSetter lookupGetter lookupSetter proto city constructor greet hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf
Now the Question is what are these extra properties , where they came?
Every object in javascript has Built in property , which is called prototype.The prototype is itself an object,so the prototype is also have its own prototype, this mechanism is called Prototype chainining.
The chain end ,when we reach prototype of own itself prototype have null value.
in the below code , we discuss , proto method and setPrototype . and also prototype inheritance
// we are declaring array
let myHeros = ["thor" , " spiderman"] // array
let dcHeros = ["batman" , "blackadmain" , "superman"] //array
Object.prototype.fuzail =function(){
console.log(`fuzail is present in all object`);
}
// i am naming this prototype is .fuzail and then we are defining the fuction in it (in above line)
myHeros.fuzail(); // i have myHeros array can ? i access this fuzail as a function ?
// i go to console and write myHeros and go to prototype[array] and then go to prototype[object]
// and then i am able to find that fuzail as a function ==> <prototype>: Object { fuzail: fuzail(), … }
const user = {
name : "top name",
email : "top@gamail.com"
}
const Teacher = {
makeVideos : true
}
const TeachingSupport = {
isAvailable : false
}
// i want all TeachingSuppoert property is available in TsAssistance
const TSAssistance = {
makeAssignment : "javasccript assign",
fullTime : true,
__proto__ : TeachingSupport // all TeachingSupport properties is available
// inside TSAssistance of prototype
}
Teacher.__proto__ = user // teacher is inherit the properties from user
// modern syntax setProtoyprof
Object.setPrototypeOf(TeachingSupport , Teacher) // whatever the teacher is doing teachingSupport is also do
// you can access all propertes of teacher from TeachingSupport
// this is called prototype inheritance