Use class Syntax to Define a Constructor Function - wtf

Can someone explain this? I have no idea what it is doing and why or what the the point is of this function…

I did pass it, but i passed because I read the directions and followed it… but I still don’t understand it.

MDN is probably the best resource for html / css / js documentation:

If you have some specific questions that are not answered on MDN, we’ll gladly try to answer them!

1 Like

First of all, do you understand what a class and a constructor mean in object oriented programming? Or more importantly, how familiar are you with Object Oriented Programming?

If you are not aware at all you may want to review those concepts first and then move back to the JavaScript implementation. You can find various resources on the matter out there but I’d often recommend a full book on the topic or maybe just a video-course.

Succinctly, a JavaScript class allows you to represent the blueprint of an object, certain properties or “state” and methods that act on that state and can be called on individual objects; you can also call “static” methods that are part of the class itself and not instances.

A constructor is a special method that returns an instance of said class and bootstraps the inner state of the object by receiving (optionally) parameters so you can do something with them at runtime, like for example, storing them in the state properties.

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;

  distanceFromOrigin() {
    return Math.sqrt(this.x * this.x + this.y * this.y);

The example here is a class called Point that represent a point in a Cartesian space with two properties (this.x and this.y) that you can fill when you instantiate the object by receiving two parameters with (potentially) the same name. this refers to any instance of said class.

There is a method called “distanceFromOrigin” that returns the distance of the point relative to the starting point (coordinate 0,0) or hypotenuse of the triangle that forms. The result of this method will be different between all of the instances of the class because each object holds its own state.

const a = new Point(5,7)
console.log(a.distanceFromOrigin()) // 8.60232527

That’s how you instantiate an object of the class and call a method on it. When you perform a new SomeClass(some arguments) you are invoking the constructor method and sending the arguments (a constructor may have no parameters) to the function that acts as the method, which in turn stores the 5 and the 7 inside this.x and this.y respectively. Then, it implicitly returns the newly created instance of the object (that’s why the method appears to be void, meaning it looks like it returns nothing – but it actually returns the object).

1 Like