Class in js


Classes are a tool that developers use to quickly produce similar objects.
let halley = {
  _name: 'Halley',
  _behavior: 0,
 
  get name() {
    return this._name;
  },
 
  get behavior() {
    return this._behavior;
  },
 
  incrementBehavior() {
    this._behavior++;
  }
}
Now, imagine you own a dog daycare and want to create a catalog of all the dogs who belong to the daycare. Instead of using the syntax above for every dog that joins the daycare, we can create a Dog class that serves as a template for creating new Dog objects. For each new dog, you can provide a value for their name.
As you can see, classes are a great way to reduce duplicate code and debugging time.

Constructor


JavaScript calls the constructor() method every time it creates a new instance of a class.
class Dog {
  constructor(name) {
    this._name = name;
    this._behavior = 0;
  }
  
  get name() {
    return this._name;
  }
 
  get behavior() {
    return this._behavior;
  }
 
  incrementBehavior() {
    this._behavior++;
  }
}

const halley = new Dog('Halley'); // Create new Dog instance
console.log(halley.name); // Log the name value saved to halley
// Output: 'Halley'
  • Dog is the name of our class. By convention, we capitalize and CamelCase class names.
  • JavaScript will invoke the constructor() method every time we create a new instance of our Dog class.
  • Inside of the constructor() method, we use the this keyword. クラスのコンテキストでは、クラスのインスタンス(インスタンスオブジェクト)を指します.In the Dog class, we use this to set the value of the Dog instance’s name property to the name argument.
  • We use the new keyword to generate a new instance of the Dog class. The new keyword calls the constructor(), runs the code inside of it, and then returns the new instance.
  • Class method and getter syntax is the same as it is for objects except you can not include commas between methods.
  • Inheritance


    When multiple classes share properties or methods, they become candidates for inheritance — a tool developers use to decrease the amount of code they need to write.
    With inheritance, you can create a parent class (also known as a superclass) with properties and methods that multiple child classes (also known as subclasses) share. The child classes inherit the properties and methods from their parent class.
    If we were to abstract the shared properties of dog and cat classes into one parent class:
    class Animal {
      constructor(name) {
        this._name = name;
        this._behavior = 0;
      }
     
      get name() {
        return this._name;
      }
     
      get behavior() {
        return this._behavior;
      }   
     
      incrementBehavior() {
        this._behavior++;
      }
    } 
    
    Now that we have these shared properties and methods in the parent Animal class, we can extend them to the subclass, Cat:
    class Cat extends Animal {
      constructor(name, usesLitter) {
        super(name);
        this._usesLitter = usesLitter;
      }
      
      get usesLitter() {
        return this._usesLitter;
      }
    }
  • The extends keyword makes the methods of the animal class available inside the cat class.
  • The super keyword calls the constructor of the parent class. In this case, super(name) passes the name argument of the Cat class to the constructor of the Animal class. When the Animal constructor runs, it sets this._name = name; for new Cat instances.
  • _usesLitter is a new property that is unique to the Cat class, so we set it in the Cat constructor.
  • In a constructor(), you must always call the super method before you can use the this keyword. - if you do not, JavaScript will throw a reference error. To avoid reference errors, it is best practice to call super on the first line of subclass constructors.
  • When we call extends in a class declaration, all of the parent methods are available to the child class.
  • Benefits of using inheritance with classes


    benefits (time saved, readability, efficiency) of inheritance grow as the number and size of your subclasses increase.
    One benefit is that when you need to change a method or property that multiple classes share, you can change the parent class, instead of each subclass.
    Now that we’ve abstracted animal daycare features, it’s easy to see how you can extend Animal to support other classes, like Rabbit, Bird or even Snake.

    Static Methods


    Sometimes you will want a class to have methods that aren’t available in individual instances, but that you can call directly from the class.
    Take the Date class, for example — you can both create Date instances to represent whatever date you want, and call static methods, like Date.now() which returns the current date, directly from the class. The .now() method is static, so you can call it directly from the class, but not from an instance of the class.
    class Animal {
      constructor(name) {
        this._name = name;
        this._behavior = 0;
      }
     
      static generateName() {
        const names = ['Angel', 'Spike', 'Buffy', 'Willow', 'Tara'];
        const randomNumber = Math.floor(Math.random()*5);
        return names[randomNumber];
      }
    } 
    
    console.log(Animal.generateName()); // returns a name
    const tyson = new Animal('Tyson'); 
    tyson.generateName(); // TypeError
  • Because of the static keyword, we can only access .generateName() by appending it to the Animal class.
  • You cannot access the .generateName() method from instances of the Animal class or instances of its subclasses
  • super() inside constructor


    I wasn't aware of this before, but you can use super to call parent class's static function.
    class Rectangle {
      static logNbSides() {
        return 'I have 4 sides';
      }
    }
    
    class Square extends Rectangle {
      static logDescription() {
        return super.logNbSides() + ' which are all equal';
      }
    }
    Square.logDescription(); // 'I have 4 sides which are all equal'

    Review

  • Classes are templates for objects. like blueprint.
  • Javascript calls a constructor method when we create a new instance of a class.
  • Inheritance is when we create a parent class with properties and methods that we can extend to child classes.
  • We use the extends keyword to create a subclass.
  • The super keyword calls the constructor() of a parent class.
  • Static methods are called on the class, but not on instances of the class.