Classical Vs Prototypal Inheritence
Classical Inheritence:
- Ways of sharing variable and methods...etc
- Very verbose
Prototypal Inheritence:
- Simpler than Classical
Example:
obj: have property prop1 so we can do obj.prop1
--Javascript Engine adds hidden properties or method to things:
All object in Javascript have a prototype property:
The property is simply a reference to another object (eg: __proto__).
It is an object that stands on its own, could use it by itself if we wanted to.
But the object property that we called __proto__ thats its prototype,
Thats the object that is going to grab and get its properties and methods
Object proto in objb has property: prop2 , so we can do obj.prop1
This is called the prototype chain.
Eg:
var person = {
firstname = 'Default',
lastname = 'Default',
getFullName: function(){
return this.firstname + this.lastname;
}
}
var john = {
firstname: 'John',
lastname: 'Doe'
}
--Alert not used this way to declare prototype as its a performance problem - DEMO PURPOSE ONLY:
john._proto_ = person;
console.log(john.getFullName());
console.log(john.firstname);
var jane = {
firstname = 'Jane'
}
jane._proto_ = person;
console.log(jane.getFullName());