Constructor confusion ... JS Newbie
In codecademys JS course, a class is defined as an object blueprint, and to call it you must add the constructor function (
constructor()
):
To create an instance, you then use the new
keyword ...
But on javascript.info this is the definition of a constructor function:
... basically the class definition from codecademy, without the specific constructor()
syntax ...
So what is a constructor function??? Is it required to use the constructor()
or not??18 Replies
In JavaScript, the
class
keyword is what's called syntactic sugar, which means it's just a simpler/nicer way to write something that has the same effect. In this case, a constructor function as shown in the javascript.info snippet. That's the original way of writing classes in JavaScript and it's also what really happens under the hood.
But since we have the class
keyword it's best to use that instead unless you have good reason not to. Just keep in mind that these are two different ways to write the same thing.
So a constructor function is a function that gets invoked immediately after a new instance of an object is created. When using class
keyword you don't technically have to provide one but of course this means you won't be able to provide arguments to better define or customize the object.
For example, this is valid JavaScript, though not very useful:
Hmm ... ok. So trying to understand ...
In the codecademy example, the most basic way of writing a class would be to exclude the
constructor()
:
And if so, why cant the parenthesis go after Dog
, like class Dog()
, as it does in the javascript.info example ...That's just the syntax of it.
class <nameOfClass> { <bodyOfClass> }
Be mindful though, no constructor may be the "most basic way" and it is correct but you will rarely not provide one.
Normally you want to define what happens when the object is created, and how many arguments it receives, in what order, etc.So basically – the javascript.info example isn't used in everyday life?
Exactly, the
class
keyword was introduced in JavaScript explicitly to replace it.
It's also more consistent with how other languages implement object oriented programming.
For example in PHP, Python, Java, Ruby... they also use the same format of class <name> <body>
Just remember, in reality, under the hood, the code that actually runs in the browser is the one from javacript.info.So if someone were to use the javascript.info syntax, the only way of knowing that it is a class blueprint is that to call it the
new
keyword is being used?this
keyword in a function it's most likely that.class
keyword was introduced so it's just the proper way now.
Actually just to clarify that, there are many other cases where you would use the this
keyword in a function. But if you see it being used to assign properties within a function, that's the tell you are looking for. That, and the new
keyword of course.Ok. Nice ... that helps a lot. So if I could drag you through the mud I'm in for a real life example.
Say you wanted a script that created a new web page everytime someone pushed a button (like a blog page in the cms), then the button would run a function that created an object based on a class called "blog post" ...?
Well I guess a simple example could look like this:
You can then have methods like that to actually output it on the browser, for example. That's just an example on how to use classes not how I would implement this.
In this example, and I understand that it is just that, an example, would the button in the cms be the
const p1
?No,
p1
is the blog post. The button would be somewhere else and it would invoke new Post(...)
somewhere along the callback.
Updated example above, though very simplistic. You would need to extract the data from somewhere else.Yes! That makes sense!
... just copied it all!
Thank you so much! My head is less swollen. 🥹
If you are curious, I asked chatGPT for an example and it looks similar with with more details:
And the explanation it gave me:
In the code above, we first define a BlogPost class with a constructor that accepts a title, body, author, and categories array. We also define a displayPost method that logs the post's details to the console.
Next, we define a generateRandomBlogPost function that generates random values for each parameter using predefined arrays. We use the Math.floor and Math.random functions to select a random value from each array.
Finally, we add an event listener to a button that, when clicked, generates a random blog post using the generateRandomBlogPost function and displays it using the displayPost method.
This code demonstrates how we can create a flexible and reusable BlogPost class that can be easily invoked and customized with random values.
--- (me again)
What you would have to do, is figure out how to obtain the values from title, author, etc. Those can probably be extracted from the HTML itself, but I asked it to give me random values and it created these examples.
Wow ... that's quite helpful actually!
What was you exact prompt?
"Write a simple example of a blog post class that gets invoked when a button is clicked. The class accepts a title, body, author and categories array. Randomize these parameters."
I find it crucial to keep the prompt short and concise, since chatGPT can go wild in its train of thought.
Yes, exactly! That's why I wanted to know what you wrote.
Again – thank you so much! This really helped clear my head on classes!
🙌
By the way, chatGPT may feel awesome and it is in many ways but I think it's best to consider it helpful tool rather than a pool of answers... it can and often does give wrong answers and if you don't know any better you may be introducing bugs in your code without knowing. Personally I try to use it only with things that I already know how to write, but it's either too tedious or don't remember the exact syntax or whatever necessary details. See rule #6 in #📝rules also.
Indeed!