I am on Day 3 of learning JavaScript. I came across this code:
class B {
constructor(name) {
this.name = name;
}
printn() {
return this.name;
}
}
class A extends B {
constructor(name, age) {
super(name);
this._age = age;
}
get age() {
return this._age;
}
printName(){
return super.printn();
}
}
let c = new A("Testing", "37");
Console.log(c.printn());
Can anybody explain what this code does. What are the constructor and super() keywords? I believe they are for inheritance? I did Google to find some tuts but this seems to be the simplest example, and it came with very little explanation.
I can't get this code to work.
That's right. The above sets up class
B
and then has classA
subclass it. Theconstructor
is the function called when you create a new instance of the class, as in thelet c = new A("Testing", "37");
line in the code. Unlike some other languages, in JavaScript there can only be one constructor for a class.super
is used in subclasses to refer to the superclass. In a constructor, you callsuper
as though it were a function, and that calls the superclass's constructor function, giving it a chance to do its initialization of the new object that was created bynew
. So for instance, inA
'sconstructor
,super()
callsB
'sconstructor
.You can also use
super
as the source of a property accessor expression to access properties (including methods) on the superclass. That's what's happening inA
'sprintName
method, where it usessuper.printName()
to callB
'sprintName
method. (Which will fail, becauseB
doesn't have aprintName
method;B
's method is calledprintn
.)I'd be remiss if I didn't point out that although this looks a lot like the class-based OOP in, say, Java or C#, it isn't. It's syntactic sugar (the good kind of sugar) for setting up JavaScript's normal prototypical inheritance using constructor functions. It hugely simplifies setting up prototypical inheritance hierarchies using constructor functions. I'd also be remiss if I didn't point out that using constructor functions to do prototypical inheritance is not necessary, you can do prototypical inheritance without using constructor functions via
Object.create
.There's a lot more to explore. MDN is probably a good starting point.
The
C
inConsole.log
shouldn't be capitalized, so changeto
Other than that, if you're using a JavaScript engine that supports
class
(such as the one in Google Chrome or Mozilla Firefox), that code works fine although note again thatA
seems to expectB
to have aprintName
method, but it doesn't, and the code at the end is callingprintn
which onlyB
has (which is fine, it just meansA
's code isn't really involved).