I'm familiar with prototypes quite well and now I try to understand how classes work by testing how they look like under the hood when compiled and compare it with 'prototypal' approach.
When I use prototypes, I can "extend" one object to another with Object.setPrototypeOf
method. I pass as the second argument anything that is of [Object] type and it works, but when I use extends
keyword with class
, it expects only another [class] type object.
This is the working prototype
-like approach:
function Citizen(country){
this.country = country;
}
function Student(subject){
this.subject = subject;
}
Object.setPrototypeOf(Student.prototype,new Citizen('Poland'));
var student = new Student('IT');
console.log(student.subject); //IT
console.log(student.country); //Poland
So, I "extends" the Student onto Citizen instance
rather than Citizen
itself (constructor). And it works just fine. I have the access to the properties of Citizen
instance (student.contry
).
How can I get the same result with the class
and extends
?
I want to achieve something like in the code below, but it throws error: Class extends value #<Citizen> is not a constructor or null
, what seems to be not as flexible as the use of pure prototypes.
class Citizen {
constructor(subject){
this.subject = subject;
}
}
class Student extends new Citizen('USA') {
//this expects CLASS rather than instance of the class
//Error: Class extends value #<Citizen> is not a constructor or null
constructor(subject){
this.subject = subject;
}
}
var student = new Student('law');
console.log(student.subject); //law