I was trying to understand javascript prototype inheritance in This Link
Then started trying below experiments on prototypes assignment for inheritance,
function Person() {}
Person.prototype.dance = function() {};
function Employee() {}
function Student() {}
Employee.prototype = new Person();
Student.prototype = new Person();
emp = new Employee();
stu = new Student();
console.log("Person Object Equal : " + (new Person() == new Person()));
console.log("Emp and Stu Prototype Equal : " + (Employee.prototype == Student.prototype));
console.log("Emp and Stu Object Prototype Equal : " + (emp.prototype == stu.prototype));
console.log("Emp and Stu Object Equal : " + (emp == stu));
If Class variables Employee.prototype==Student.prototype
is returning false,
then how Object variables emp.prototype==stu.prototype
is returning true?
I was thinking that emp.prototype==stu.prototype
will also return false as they would be pointing to the same prototypes as its class functions.
Can somebody please explain whats exactly the logic behind this? Maybe I am missing some point here..?
You can copy above code and run for testing in the Same Link provided above.
The reason that third check returns true is simply that stu.prototype
and emp.prototype
are both undefined. .prototype
is a property that exists on the constructor function; it does not exist on the object created by new
ing that constructor.
emp does have a emp.__proto__
property, but this is deprecated and you shouldn't access it directly. emp.__proto__ === Employee.prototype
will return true. The non-deprecated approach for accessing the prototype would be Object.getPrototypeOf(emp)
, though even that you'll rarely have reason to use.