I have following code:
export class Utils{
constructor() {
this.dateFormat = "MM-DD-YY";
}
static getFormat() {
return this.dateFormat;
}
}
when I am trying to import this class to other file and try to call the static method gteFormat
it return undefined
. Here is how I am doing it:
import * as Utils from "./commons/Utils.js";
class ABC {
init(){
console.log(Utils.Utils.getFormat());// gives undefined
}
}
How can I make this static method return the dateFormat
property?
If you are conceptually working with a bunch of functions, you can consider relying on the module scope itself for privacy, rather than the class structure. Then you can export functions or values directly. Like
const dateFormat = "MM-DD-YY";
export function getFormat() {
return dateFormat;
}
with usage like
import * as Utils from "./commons/Utils.js";
console.log(Utils.getFormat())
or even
import { getFormat } from "./commons/Utils.js";
console.log(getFormat())
or if it's literally a constant you can export it directly
export const DATE_FORMAT = "MM-DD-YY";
then
import { DATE_FORMAT } from "./commons/Utils.js";
console.log(DATE_FORMAT);
Exporting a class with a bunch of static methods is a very Java-y way to write it, and the class itself adds nothing.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments