ES6: Use class Syntax to Define a Constructor Function

Dear Members,

Please solve my concept about constructor, why constructor is used in js whereas we have functions to used easily.

please see the code below. what’s going on in code ? what is this keyword used for.


class SpaceShuttle {
  constructor(targetPlanet){
    this.targetPlanet = targetPlanet;
  }
}
const zeus = new SpaceShuttle('Jupiter')

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

At the beginning the use of classes is confusing in JavaScript, but it’s an important concept to learn Object-Oriented Programing and modern frameworks.


class SpaceShuttle {
  constructor(targetPlanet){
    this.targetPlanet = targetPlanet;
  }
}

The class creates a model for objects, with the basic elements for everything you create from it. In your example, you are creating a class, or a model, for a SpaceShuttle which must have a targetPlanet. In other words, every SpaceShuttle must have adestiny to go.

const zeus = new SpaceShuttle('Jupiter')

Here you are creating a new SpaceShuttle called zeus, which must travel to Jupiter! If you want to learn more about Object-Oriented Programming and why we use classes instead of function you can find useful information here https://www.freecodecamp.org/news/an-intro-to-object-oriented-programming-in-javascript-objects-prototypes-and-classes-5d135e7361b1/

1 Like