Classes in JavaScript. Сreation, properties and methods. Co... open

Classes in JavaScript. Сreation, properties and methods. Code examples

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators

With the introduction of the ES2015 (ES6) standard, JavaScript has a new way of defining objects – using classes.

Objects in JavaScript ES5. Code example open
Objects in JavaScript ES5. Code example
August 16, 2022
srgey@gmail.com

A class is an object template that describes its properties, state, and behavior.
A class object is a specific implementation or instance of a class. Many instances can be created from one class.

Creating a class

The class keyword is used to define a class:

    class User { }

User is the name of the class, and the body of the class is in curly brackets. This is the most common way to define a class. But there are other ways too. So, you can also define anonymous class and assign it to a variable or constant:

const User = class { }

We can create a non-anonymous class and assign it to a variable or constant:

    const User = class Person { }

Creating an object

After the class is defined, we can create objects of the class using the constructor:

    class Person { }

    const alex = new Person();
It is worth noting that, unlike functions, in order to use a class, it must first be defined.

For example, in the following code, we will get an error because we are trying to use the class before it is defined:

const alex = new Person(); // !Error - Uncaught ReferenceError: Cannot access 'Person' before initialization

class Person{}

If a class definition is assigned to a variable or constant, then we can use the name of that variable/constant to creating class objects:

    const User = class Person { }
    const tom = new User();
    console.log(tom);

An example of creating an anonymous class object:

    const Person = class { }
    const tom = new Person();
    console.log(tom);

Class properties

Fields and properties are used to store the data or state of an object in a class:

    //create a class
    class Person {
    //initializing the properties
        name;
        age;
    }

    const alex = new Person();//create an instance of the class

    alex.name = "Alex";//set the value of the name property
    alex.age = 33;//let's set the value of the age property
    console.log(alex.name);  //Alex
    console.log(alex.age);   //33

If necessary, we can assign some initial values to the fields:

    //let's create a class and set certain initial values to its properties
    class Person {
        name = "Alexander";
        age = 33;
    }

    const alex = new Person();

    console.log(alex.name);  //Alexander

    alex.name = "Tom";//overwrite the property of the object

    console.log(tom.name); // Tom

Class methods

In addition to storing properties (data), the class can store methods that can work with them. In essence, these are functions that belong to the class or class object.

For example, let’s create several methods:

    class Person {
        //initializing the properties
        name;
        age;
        //let's create methodsї 
        move(place) {
            console.log(`Go to ${place}`);
        }

        enter() {
            console.log("Person Enter");
        }
    }
    const alex = new Person();//create an instance of the class

    alex.move("Cinema"); // Go to Cinema
    alex.move("Home");// Go to Home
    alex.enter();//Person Enter

You will learn why the function does not see the parameters that we pass to the method below.

This

Inside the class body, the this keyword points to the class itself, and with its help we can easily refer to it properties and methods inside the class.

Consider an example:

    //create a class
    class Person {
        name;
        age;
        print() {
            console.log(`Name: ${this.name}  Age: ${this.age}`);//through the keyword this, we will refer to the properties of the object
        }
    }

    //create an instance of the class
    const alex = new Person();

    //let's set the properties for the object alex
    alex.name = "Alexander";
    alex.age = 33;

    //let's use the object method
    alex.print(); // Name: Alexander  Age: 33

Constructor definition

A constructor is used to create an object of a class:

    const alex = new Person();
A call to a default constructor that exists in classes is actually a call to a method that has the same name is the same as the class, and returns an object of that class.

We can define our own constructors in classes:

    class Person {
        
        name;
        age;

        constructor() {
            console.log("I am constructor");
        }

    }
    const alex = new Person();   // I am constructor

Basically, the purpose of a constructor is to initialize an object with some initial data:

    class Person {

        name;
        age;

        constructor(personName, personAge) {
            this.name = personName;
            this.age = personAge;
        }

        print() {
            console.log(`Name: ${this.name}  Age: ${this.age}`);
        }

    }
    const alex = new Person("Alexander", 33);

    alex.print();// Name: Alexander  Age: 33

    const bob = new Person("Bob", 41);

    bob.print() // Name: Bob  Age: 41

Here the constructor takes two parameters and passes their values to the class fields. Accordingly, when creating an object, we can pass the appropriate values for these parameters to the constructor.

It is worth noting that in the example below the class field definitions are redundant. Accessing fields in the constructor via this in fact, it will be similar to their definition, and in this case we can remove the definition of the fields:

    class Person {

        constructor(personName, personAge) {
            this.name = personName;
            this.age = personAge;
        }

        print() {
            console.log(`Name: ${this.name}  Age: ${this.age}`);
        }

    }
    const alex = new Person("Alexander", 33);

    alex.print();// Name: Alexander  Age: 33

    const bob = new Person("Bob", 41);

    bob.print() // Name: Bob  Age: 41
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation