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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.59.219