I am on Day 3 of learning JavaScript. I came across this code:
class B {
constructor(name) {
this.name = name;
}
printn() {
return th
Welcome to JavaScript. Good luck on your journey. I will recast your question from your specific issues to the more general question of how best to learn JavaScript.
First, make sure you've organized your environment, starting with your editor or IDE. Whichever one you choose, it should help you format, indent, highlight, check, and possibly even run your code. Spend time learning how to configure it to your liking. Install useful plug-ins. You will spend many hours in your IDE. Take the same care to furnish it as you would your house.
Next, make sure you understand where to find information. Some people on SO seem to think that it is a human-powered documentation service. MDN is almost always the best resource. They also provide tutorials, which would be a fine place to start.
Next, get very familiar with Chrome devtools. Read the documents from beginning to end. Learn how to use the console, and the source panel, and breakpoints, and variable watches. At the end of the day, you have to debug your own programs, although some people on SO seem to think they can depend on the community to do that.
Now on to the language itself. Before diving into classes, if you haven't already I'd make sure you are very comfortable with the basics: data types including objects and arrays, and basic control structures like conditionals and loops. You should understand exactly what an object is, what a property is, how to write objects in literal form, how to set and retrieve properties, and the equivalent concepts for arrays. Continuously write little programs to try things out; you can run them in the devtools console.
Make sure you have a solid understanding of functions. They are the fundamental building blocks of JS logic. They are parameterized bundles of logic that take well-defined inputs (parameters) and produce well-defined outputs (return values). Learn how to define functions, and how to call them. When you approach a problem, it is almost always a good starting point to think about how it can be broken down into sub-problems that can be implemented as functions.
Once you are comfortable with arrays and functions, make sure you have a firm grasp of the array methods (functions) which take functions as parameters. That's right; in JavaScript, functions are values which can be passed to other functions as parameters. This is your first gentle introduction to functional programming. Learn forEach
and related array methods, where you pass a function to tell it what to do with each element.
If you are doing front-end work, you will need to be very familiar with the DOM. Go back to devtools and make sure you understand how to examine the DOM using the Elements panel. Learn the basic DOM APIs for creating elements, setting their attributes, inserting them into the DOM, and finding them in the DOM, such as getElementById
. Again, as you go along, continuously write little sample programs to confirm that you are on the right track and reinforce your knowledge. In tandem with mastering the DOM, you will need to begin learning CSS, which is the way we manage properties which control how DOM elements are styled (layed out and formatted), and CSS classes, which are bundles of those properties that can be applied by simply assigning a class to an element. Take time to grasp the cascade, which is the process by which the CSS engine decies which rule to apply to which element. Go back to devtools once more and make sure you understand how to examine CSS properties in the DOM using the style inspector.
You'll notice that we haven't even mentioned JS classes yet, which is what your question here is about. I'm a little surprised that you would be delving into this topic so early in your learning process. Classes are the foundation of a particular style of program design generally known as object-oriented programming, or classical OOP, which involves designing objects which are bundles of data and related functionality. There are people who believe that all programming is, or should be, OOP. There are other people who successfully write large systems without using any OOP principles at all.
The problem with OOP is that the real world does not divide itself neatly into Animals and Dogs and Vehicles and Cars and As and Bs. After you've defined Animals and Dogs then you realize that you need Mammals in between, and before you know it you end up with a contorted class hierarchy that is hard to understand, maintain, and extend, and which you spend half your time re-arranging. It's quite likely that none of this machinery is going to be necessary for the IRL problems you are trying to solve. Once you have the OOP hammer, everything starts looking like a nail. Before long you will be pounding with your new OOP hammer on strands of limp spaghetti and blobs of jello, or simply waving it in the air.
What is the constructor and super() keyword. I believe it is for inheritance?
That's right. The above sets up class B
and then has class A
subclass it. The constructor
is the function called when you create a new instance of the class, as in the let 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 call super
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 by new
. So for instance, in A
's constructor
, super()
calls B
's constructor
.
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 in A
's printName
method, where it uses super.printName()
to call B
's printName
method. (Which will fail, because B
doesn't have a printName
method; B
's method is called printn
.)
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.
I can't get this code to work.
The C
in Console.log
shouldn't be capitalized, so change
Console.log(c.printn());
to
console.log(c.printn());
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 that A
seems to expect B
to have a printName
method, but it doesn't, and the code at the end is calling printn
which only B
has (which is fine, it just means A
's code isn't really involved).
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.printName();
}
}
let c = new A("Testing", "37");
console.log(c.printn());