Below is my sample code,
function Employee(name){
this.name = name;
}
Employee.prototype.getName = function(){
return this.name;
}
var a = new Employee("a");
function Manager(name){
this.name = name;
}
var b = new Manager("b");
//Case:1
Manager.__proto__ = Employee.prototype;
console.log(b.getName());
//Case:2
b.__proto__.__proto__ = Employee.prototype;
console.log(b.getName());
Case: 1 When the Manager's dunder proto is pointing to the Employee prototype it produces TypeError(TypeError: b.getName is not a function).
Case: 2 However in this case when the Employee prototype is pointed starting from the Manager's instance dunder proto(i.e. b.__proto__
), this would work fine and gives the correct result.
According to the law of inheritance,
1. instance 'b' initially looks for the function getName
in itself if it was created through the constructor mode.
2. Else would look for the getName
in Manager's prototype object.
3. Now the next level is Object.prototype
.
Please correct me if I am wrong in any sense.
But I would wish to point the Manager's __proto__
to Employee prototype instead of Object.prototype
.
I tried to achieve this by Manager.__proto__ = Employee.prototype;
and b.__proto__.__proto__ = Employee.prototype;
. Only the latter worked correctly.
Why did Manager.__proto__ = Employee.prototype;
throw TypeError
when both the methods are pointing to Employee prototype??