Notes
Prototype Inheritance
Content of the notes (1)
Page 1
Prototype Inheritance:
-JS only have prototype inheritance
Lets take first example:
let dragon = {
name:'Tanya',
fire: true,
fight(){
return 5
}
sing(){
return `I am ${this.name} breatehr of fire'
}
}
let lizard= {
name:'kiki',
fight(){
return 2
}
}
const singLizard = dragon.sing.bind(lizard)
console.log(singLizard);
================OUTPUT==========normal
I am Kiki, breather of fire
2) What if i modify sing function
let dragon = {
name:'Tanya',
fire: true,
fight(){
return 5
}
sing(){
if(fire){
return `I am ${this.name} breatehr of fire'
}
}
}
let lizard= {
name:'kiki',
fight(){
return 2
}
}
const singLizard = dragon.sing.bind(lizard)
console.log(singLizard);
==============OUTPUT============
undefined
How can we fix the error which we got above???
Answer is prototype inheritance
Here is thr fix:
let dragon = {
name:'Tanya',
fire: true,
fight(){
return 5
}
sing(){
if(fire){
return `I am ${this.name} breatehr of fire'
}
}
}
let lizard= {
name:'kiki',
fight(){
return 2
}
}
lizard.__proto__=dragon
lizard.sing();
================OUTPUT=========
I am Kiki, breather of fire
Information
- Description
- Note on Prototype Inheritance, created by Shilpa Sharma on 19/08/2019.
- Created by
- Shilpa Sharma
- Views
- 0
- Rating