0

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??

Geek Num 88
  • 5,264
  • 2
  • 22
  • 35
  • What is "dunder"? – Bergi Sep 05 '16 at 17:41
  • `b.__proto__ === Manager.prototype !== Manager` – Bergi Sep 05 '16 at 17:43
  • Agreed. So the only way to access any Object's prototype is through an istance(`b.__proto__.__proto__`) is it?? Because `Manager.prototype.__proto__` is not a valid operation. – DeepakBilikere Sep 06 '16 at 05:01
  • `b.__proto__.__proto__` is exactly the same as `Manager.prototype.__proto__` - not sure what you mean by "not a valid operation"? The only invalid thing here is the use of the deprecated `__proto__` property. – Bergi Sep 06 '16 at 05:53

0 Answers0