Day 7 of 16— ”Classes I”
--
This story is part of a series that has been initiated here:
Day 0 — ”How to run TypeScript”
If you want to follow all code examples, you should consult this to find some guidance on how to quickly set up a small TypeScript project.
If you come from an object-oriented language then what follows might be quite familiar to you. In this story, I want to present some more advanced features of classes which are very useful to know.
Classes end up being functions
If you create a class like
export class A{
aField: string = 'hello A';
aMethod(){
}
}
and compile it to JavaScript, then the output looks similar to
...
function A() {
this.aField = 'hello A';
}
A.prototype.aMethod = function () {};
...
You observe, the class has compiled to what is considered a ‘classic’ class in JavaScript. Fields are added to the object ( this.aField = ...
) and method are put on the function’s prototype ( A.prototype.aMethod = ...
).
Inheritance and prototype chaining
If you inherit a class A from a class B like so
class B {
bField = 'b';
bMethod(){};
}class A extends B {
aField = 'a';
aMethod(){};
}
and compile this, then the outcome looks similar to this:
function B() {
this.bField = 'b';
}
B.prototype.bMethod = function () { };function A() {
var _this = B.apply(this, arguments); // inheriting fields from B
_this.aField = 'a'; // defining/overwriting own fields
return _this; // returning the instance
}
__extends(A, B);
A.prototype.aMethod = function () { };
where __extends(A, B)
in principle is doing this:
A.prototype = Object.create(B.prototype); // a new(!) object with prototype of B
A.prototype.constructor = A; // setting the…