Prototype Inheritance
Example 1:
function Person(name, rank) {
this.name = name;
this.rank = rank;
}
//Replacing the function prototype of this constructor function, with an object that has all the methods I want that object to have
Person.prototype = {
sayName: function(){
console.log("Hello" + this.name);
},
firePerson: function(person) {
return false;
}
};
var nelson = new Person("Nelson", 1);
var joe = new Person("Joe", 3);
console.log(nelson.firePerson(joe)); -> Returns false
//We need the manager to inherits from the Person
function Manager(name, rank) {
this.name = name;
this.rank = rank;
}
//Totally wrong way to do would be:
Manager.prototype = Person.prototype; //A bit closer, but it is bad!!
//Potential Solution, bit closer, but firePerson method still return false, not overridden:
function Manager(name, rank) {
Person.call(this, name, rank);
}
//We could do this to get the firePerson method to work, but still wrong!
function Manager(name, rank) {
Person.call(this, name, rank);
this.firePerson : function(person) {//Its making a copy of this function everytime, we want the firePerson function to be on the Prototype
return rank > person.rank;
}
}
//We want the firePerson function to be on the Prototype of the Manager
//Still have a problem, normal people can still fire people!
Manager.prototype = Person.prototype;
Manager.prototype.firePerson = function(person) {
return this.rank > person.rank; //If we do joe.firePerson(nelson) -> Will return true
//It is because we are redefined the firePerson function on the actual Person prototype.
//We did Manager.prototype = Person.prototype;
//If we make any change in the Manger.prototype we are also changing the Person.prototype
}
----Solution---
//We need to make a copy of the Person.prototye:
//Couple of ways:
1. Manager.prototype = {__proto__: Person.prototype};
2. Manager.prototype = Object.create(Person.prototype); //Proper way cross platform
var steve = new Manager("Steve", 10);
console.log(nelson.firePerson(joe)); -> Returns true