Modern JavaScript Web Development Cookbook
上QQ阅读APP看书,第一时间看更新

Static methods

Often, you have some utility functions that are related to a class, but not to specific object instances. In this case, you can define such functions as static methods, and they will be available in an easy way. For instance, we could create a .getMonthName() method, which will return the name of a given month:

// Source file: src/class_persons.js

class ExtDate extends Date {
static getMonthName(m) {
const months = [
"JAN",
"FEB",
.
.
.
"DEC"
];
return months[m];
}
fullDate2() {
return (
ExtDate.getMonthName(this.getMonth()) +
" " +
String(this.getDate()).padStart(2, "0") +
" " +
this.getFullYear()
);
}
}

console.log(new ExtDate().fullDate2()); // "MAY 01 2018"
console.log(ExtDate.getMonthName(8)); // "SEP"

Static methods must be accessed by giving the class name; since they do not correspond to objects, they cannot be used with this or an object itself.