Page 179 - JavaScript
P. 179

};

         classInstance.prop = 10;

         console.log(classInstance.prop); // logs: 5



        Class Inheritance


        Inheritance works just like it does in other object-oriented languages: methods defined on the
        superclass are accessible in the extending subclass.

        If the subclass declares its own constructor then it must invoke the parents constructor via super()
        before it can access this.


         class SuperClass {

             constructor() {
                 this.logger = console.log;
             }

             log() {
                 this.logger(`Hello ${this.name}`);
             }

         }

         class SubClass extends SuperClass {

             constructor() {
                 super();
                 this.name = 'subclass';
             }

         }

         const subClass = new SubClass();

         subClass.log(); // logs: "Hello subclass"


        Private Members


        JavaScript does not technically support private members as a language feature. Privacy -
        described by Douglas Crockford - gets emulated instead via closures (preserved function scope)
        that will be generated each with every instantiation call of a constructor function.


        The Queue example demonstrates how, with constructor functions, local state can be preserved
        and made accessible too via privileged methods.


         class Queue {

           constructor () {                    // - does generate a closure with each instantiation.

             const list = [];                  // - local state ("private member").





        https://riptutorial.com/                                                                             136
   174   175   176   177   178   179   180   181   182   183   184