Static properties and methods

// 創造 class 自己的方法用 static
class User {
  static staticMethod() {
    alert(this === User);
  }
}

User.staticMethod(); // true

// 跟一般函式創造自己的屬性一樣
function User() { }

User.staticMethod = function() {
  alert(this === User);
};

// 一般來說,靜態屬性用來增加專屬於 class 的方法,不屬於任何用 new class 創造的物件
class Article {
  constructor(title, date) {
    this.title = title;
    this.date = date;
  }

  static compare(articleA, articleB) {
    return articleA.date - articleB.date;
  }
}
// usage
let articles = [
  new Article("HTML", new Date(2019, 1, 1)),
  new Article("CSS", new Date(2019, 0, 1)),
  new Article("JavaScript", new Date(2019, 11, 1))
];

articles.sort(Article.compare);

alert( articles[0].title ); // CSS

// 創造新的文章
class Article {
  constructor(title, date) {
    this.title = title;
    this.date = date;
  }

  static createTodays() {
    // remember, this = Article
    return new this("Today's digest", new Date());
  }
}

let article = Article.createTodays();

alert( article.title ); // Todays digest

// 靜態方法常用於與數據庫有關的物件
// assuming Article is a special class for managing articles
// static method to remove the article:
Article.remove({id: 12345});

Statics and inheritance

// 靜態方法會被繼承
class Animal {

  constructor(name, speed) {
    this.speed = speed;
    this.name = name;
  }

  run(speed = 0) {
    this.speed += speed;
    alert(`${this.name} runs with speed ${this.speed}.`);
  }

  static compare(animalA, animalB) {
    return animalA.speed - animalB.speed;
  }

}

// Inherit from Animal
class Rabbit extends Animal {
  hide() {
    alert(`${this.name} hides!`);
  }
}

let rabbits = [
  new Rabbit("White Rabbit", 10),
  new Rabbit("Black Rabbit", 5)
];

rabbits.sort(Rabbit.compare);

rabbits[0].run(); // Black Rabbit runs with speed 5.

// extends gives Rabbit the [[Prototype]] reference to Animal
class Animal {}
class Rabbit extends Animal {}

// for static properties and methods
alert(Rabbit.__proto__ === Animal); // true

// the next step up leads to Function.prototype
alert(Animal.__proto__ === Function.prototype); // true

// the "normal" prototype chain for object methods
alert(Rabbit.prototype.__proto__ === Animal.prototype);

Last updated