DEV Community

Cover image for JavaScript Classes pt. 1
Wonuola
Wonuola

Posted on

JavaScript Classes pt. 1

This is a short summary of JS classes and the get() property

A JavaScript class is an outline from which objects are created. It provides a much simpler and clearer syntax and makes inheritance of attributes easier. It can be referred to as "special functions."

You can define a class by using a class declaration. To do so, use the class keyword, which is the class itself.

Class expressions

There are two ways to define or express a class.

Named
let animals = class lion {
}

Here, "lion" is the class name, and "animals" is the variable name that represents the class wherever it is mentioned.

Unnamed
let animals = class{
}

Here, there is no name to represent the class. Just like with functions, it could either be named

//named
(function animals(){})
// unnamed
(function(){})

When dealing with JS classes, one needs to write with extra caution as code written in the body is exposed to stricter syntax and silent errors could be thrown for increased performance of your code.

Constructors

They are methods that assign properties, create and initialize objects created with a class.

N.B There can only be one constructor, but a constructor can use the super () keyword to call the constructor of the super class.

It starts with the word "constructor," then you add in the variables. Example

class Animal {
// the constructor keyword
constructor ( spiece, kingdom) {
this.specie = specie;
this .kingdom = kingdom;
}
}

The get () keyword

This is a special keyword as it binds an object property to a function. It is referred to as a property rather than a method, because whenever this property is called it activates the getter function.

Then the return value of this getter value then determines which property is returned.

You can use it to show the status of an internal variable without having to use explicit method calls.

Please Note;
It must have zero parameters.
It must not appear in an object literal with another get () keyword

example : { get x() {}, get x(){}}

It must not appear alongside another data entry for the same property x:..., get().

To delete the get () property

delete.const.getter's name ()

E.g. delete.const.animals()

Don't forget to drop your comments!

Discussion (0)