DEV Community

Cover image for JavaScript Classes
Hanna
Hanna

Posted on

JavaScript Classes

A bit about class in js.

Alt Text

Class Methods

class Animal {
  constructor(name, legs) { ... }
  speech() { ... }
  numberOfLegs() { ... }
}
const dog = new Animal();
const cat = new Animal();
const spider = new Animal();
Enter fullscreen mode Exit fullscreen mode

The code above defines a class ClassName. The curly braces { } delimit the class body.
The class becomes useful when you create an instance of the class (dog, cat, spider). An instance is an object containing data and behavior described by the class.

ALWAYS add a method named constructor(). It is executed automatically when a new object is created and is used to initialize object properties.
Animal’s constructor has two parameters name and legs, which is used to set the initial value of the fields this.name, this.legs.

new Animal() creates instances of the Animal class.

                    SO...

"CLASS is used to describe one or more objects. 
It serves as a template for creating, or 
instantiating, specific objects within a program. 
While each object is created from a single class, 
one class can be used to instantiate multiple 
objects."
Enter fullscreen mode Exit fullscreen mode

Top comments (0)