DEV Community

Ruxin Qu
Ruxin Qu

Posted on • Updated on

JavaScript: OOP-Class

  1. Classes are templates for objects. The name of a class should have the first letter capital and the rest in camalcase.
  2. An instance is an object that contains the property name and method of a class.
  3. When we create a new instance with the keyword new, the constructor method is called. Note: class methods and getter syntax are the same with objects. BUT no commas between methods.
  4. To call a method: instance.methodname()
  5. Inheritance allows the child class to use share property and method. The extend keyword makes the method and getters of parent class available in the child class. The super keyword calls the constructor method in the parent class.
  6. Static method can only be called directly from the class. It can't be used on an instance of a class or subclass. (don't forget the () at the end) example code:
class Animal {
    constructor(breed, gender) {
        this._breed = breed;
        this._gender = gender;
        this._vaccine = 0;
    get breed() {
        return this._breed;
    get gender() {
        return this._gender;
    get vaccine() {
        return this._vaccine;
    vaccineShot(num) {
        this._vaccine += num;
    static generateName(){
        const nameArr=['Milo','Cookie','Sandy','Odin'];
        return nameArr[Math.floor(Math.random()*3)]
class Dog extends Animal {
    constructor(breed, gender, age) {
        super(breed, gender);
        this._age = age;
    get age(){
        return this._age;
const dahuang = new Dog('Golden Retriever', 'Male',1);
//Output: DogHome { _breed: 'Golden Retriever', _gender: 'Male', _vaccine: 2, _age: 1 }
//Output: 2
//Output: 2
//Output: Milo

Enter fullscreen mode Exit fullscreen mode

Top comments (0)