For instance :
class Parent {
foo() {
console.log("foo");
}
}
class Child extends Parent {
bar() {
console.log("bar");
}
}
Here, the expression
Object.getPrototypeOf(Child) === Parent
would evaluate to true.
Now I understand the basics of prototypical inheritance and how classes work in Javascript that is, every function has a prototype property, which is copied on to the newly created class instance's __proto__ property upon calling the function with the new operator
I also understand that Object.getPrototypeOf essentially returns the __proto__ property of any given object and generally we simulate inheritance in pure javascript by the means of setting the prototype property of the child class to an instance of the parent class, like this :
function Parent(){}
Parent.prototype.foo = function(){
console.log("foo");
}
function Child(){}
// Inherit properties from Parent
Child.prototype = new Parent();
My questions are :
what does the result of Object.getPrototypeOf when called with a class as an argument represent ? How is it linked to class inheritance in TS/JS ?
Is it safe to use Object.getPrototypeOf to check if whether a particular class extends another class at runtime ?
The extends keyword does two things:
It sets the SuperClass.prototype object as the prototype of the SubClass.prototype object. In your case, Child.prototype gets Parent.prototype object as its prototype.
It also sets the super class' constructor as the prototype of the child class constructor. In your case, Child constructor gets Parent constructors as its prototype.
Above two statements essentially mean the following in code:
class Parent {}
class Child extends Parent {}
console.log(Object.getPrototypeOf(Child.prototype) === Parent.prototype);
console.log(Object.getPrototypeOf(Child) === Parent);
In other words, the extends keyword sets up two prototype chains:
Child.prototype ---> Parent.prototype ---> Object.prototype
Child ---> Parent ---> Function.prototype ---> Object.prototype
So, Object.getPrototypeOf(Child) simply returns the Parent constructor.