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

Last updated

Was this helpful?