"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Understanding Class Fields and Static Properties

Understanding Class Fields and Static Properties

Published on 2024-11-08
Browse:943

Understanding Class Fields and Static Properties

Hello! Welcome to this article about Class Fields and Static Properties!
ES15 added the ability to define class fields and static properties directly within the class body. This eliminates the need for constructor functions to initialize properties, leading to cleaner and more concise code. This is about understanding this new feature!

1. Define a class.

You need to define a class to use it:

class myClass {
}

2. Put the properties in the class.

Putting the properties in the class defines the properties:

class myClass {
    property1;
    property2;
}

You can add as many properties as you need.

3. Add the constructor() function.

Add the constructor function to define the keys in the this object for the properties:

class myClass {
    property1;
    property2;
    constructor(property1, property2) {
        this.property1 = property1;
        this.property2 = property2;
    }
}

4. Example

This is an example of using this new feature in JS:

class Person {
    name;
    age;
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}

5. Conclusion

And that is the conclusion for this post!
Make sure you add a reaction and bookmark this!
Also make sure you comment down below!
This post was made for The Frontend Challenge!

Release Statement This article is reproduced at: https://dev.to/pilagerplayz/understanding-class-fields-and-static-properties-2hce?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3