Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

class
javascript

What are classes in Javascript?

Educative Answers Team

Does Javascript have classes?

Classes are bits of code that encompass multiple objects, methods and allow manipulation for its member variables and functions. Within each language, a class has different syntax and the same holds true for Javascript.

In this language, a class is simply a variant of functions. Using the class functionality one can define the constructor and the prototype functions for the member objects in one encompassing block.

How do you create a class?

To create a class in Javascript, a few things should be noted:

  • A class is created using the keyword class as shown in the example below:
class Student{
  // Elements within the class are declared and defined inside the brackets
}
  • A class has a default constructor which is empty but can also be defined within the class method. Unlike in other languages, to declare the constructor, Javascript has a specific keyword called constructor. The parameter(s) given to the constructor are then used to define elements within the class; class members.

  • The example below shows how this is done:

class Student{
    //Declaring the constructor
    constructor(name){this.name=name;}
}
  • Multiple methods can be defined in a Javascript class and they need not be separated by a , as shown in the example below:
class Student{
//This is the class constructor
    constructor(name){this.name=name;}
//There is no comma between the two methods
//This is a method defined in the class; member method
    displayStudentname(){console.log(this.name);}
}
  • An instance of a class is defined using the keyword new. To see how this is done, look at the code below:
class Student{

    constructor(name){this.name=name;}

    displayStudentname(){console.log(this.name);}
}
//Creating an instance of a class
let studentOne = new Student("JohnDoe");
studentOne.displayStudentname();

Note: All classes in Javascript use strict mode.

RELATED TAGS

class
javascript
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring