Page 177 - JavaScript
P. 177

Class Constructor


        The fundamental part of most classes is its constructor, which sets up each instance's initial state
        and handles any parameters that were passed when calling new.

        It's defined in a class block as though you're defining a method named constructor, though it's
        actually handled as a special case.


         class MyClass {
             constructor(option) {
                 console.log(`Creating instance using ${option} option.`);
                 this.option = option;
             }
         }


        Example usage:


         const foo = new MyClass('speedy'); // logs: "Creating instance using speedy option"


        A small thing to note is that a class constructor cannot be made static via the static keyword, as
        described below for other methods.


        Static Methods


        Static methods and properties are defined on the class/constructor itself, not on instance objects.
        These are specified in a class definition by using the static keyword.


         class MyClass {
             static myStaticMethod() {
                 return 'Hello';
             }

             static get myStaticProperty() {
                 return 'Goodbye';
             }
         }

         console.log(MyClass.myStaticMethod()); // logs: "Hello"
         console.log(MyClass.myStaticProperty); // logs: "Goodbye"


        We can see that static properties are not defined on object instances:


         const myClassInstance = new MyClass();

         console.log(myClassInstance.myStaticProperty); // logs: undefined


        However, they are defined on subclasses:


         class MySubClass extends MyClass {};

         console.log(MySubClass.myStaticMethod()); // logs: "Hello"
         console.log(MySubClass.myStaticProperty); // logs: "Goodbye"


        https://riptutorial.com/                                                                             134
   172   173   174   175   176   177   178   179   180   181   182