Function Constructor vs Class

синтаксис

Функция - конструктор

 

этим цветом выделено различие в синтаксисе


function Human (name = "Unknown") {
    this.name = name;
}
function ~ class & constructor

                

Методы


function Human (name = "Unknown") {
    this.name = name;
}
Human.prototype.hello = function () {
    return `Hello ${this.name}!`
}
Human.prototype.hello ~ hello

                

Наследование


function Human (name = "Unknown") {
    this.name = name;
}
function Student (name, group = "FE") {
        Human.apply(this,arguments);
        this.group = group;
}
Student.prototype = new Human(); 

super ~ apply
extends ~ prototype
                

Class

этим цветом выделено сходство в синтаксисе


class Human {
    constructor(name = "Unknown") {
        this.name = name;
    }
}
                

Methods


class Human {
    constructor(name = "Unknown") {
        this.name = name;
    }
    hello () {
        return `Hello ${this.name}!`
    }
}
                

Inheriting


class Human {
    constructor(name = "Unknown") {
        this.name = name;
    }
}
class Student extends Human {
    constructor(name, group = 'FE') {
            super(name)
            this.group = group;
    }
}
                

Наследование методов / Inheritaning of methods

Синтаксис наследования extends и super


   class Family {
      constructor (name, birthday){
         this.name = name;
         this.birthday = birthday;
         this.age = 0;
      }
         setAge () {
            this.age = (new Date()).getFullYear()
               - this.birthday.getFullYear();
            return this;
         }

         getAge () {
            return this.age;
         }
   }
   const homer = new Family('Homer', new Date(1981, 1, 10));
   homer.setAge().getAge()
   37
   class Child extends Family {
      constructor (name, birthday) {
         super(name, birthday);
      }
   }
   const bart = new Child('Bart', new Date(2008, 3, 1));
   bart.setAge().getAge()
    10
    

Cтатические методы / Static methods

Cтатические методы вызываются через имя класса, например Method.random()

Обращение к статическим методам через объект приводит к ошибке is not a function

Синтаксис static


class MyMath {
    static one () {
        return 1;
    }
}
MyMath.one()
1
        

Вызов из другого статического метода this


class MyMath {
    static one () {
        return 1;
    }
    static ten () {
        return this.one() * 10;
    }
}
MyMath.one()
MyMath.ten()
1
10
        

Вызов из метода (нестатического) this.constructor


class MyMath {
    static one () {
        return 1;
    }
    ten () {
        return this.constructor.one() * 10;
    }
}
const obj = new MyMath()
obj.ten()
10
        

Переопределене при наследовании super


class AlterMath extends MyMath {
    static one () { return super.one() * 100; }
}

AlterMath.one()
100
        

Требуется запомнить