如何在 javascript es6 class 构造函数中声明一个对象

how to declare an object in javascript es6 class constructor

我在 class 构造函数中声明了一个 属性 并通过方法访问,它被声明为 'static',使用 'this' 并且它不可访问。如何访问静态方法中的构造函数 (class) 变量?

export class Reporter {
    constructor() {
        this.jsonReports = path.join(process.cwd(), "/reports/json")

        this.cucumberReporterOptions = {
            jsonFile: targetJson,
            output: htmlReports + "/cucumber_reporter.html",
            reportSuiteAsScenarios: true,
            theme: "bootstrap",
        }
    }

    static createHTMLReport() {
        try {
            reporter.generate(this.cucumberReporterOptions);
        } catch (err) {

        }
    }
}

已更新:

根据“@CodingIntrigue”,我在 'reporter.js' 文件中这样做,并在我的配置文件中将方法称为 Reporter.createHTMLReport() 并按预期工作。但不确定这是否是最佳做法。

const jsonReports = path.join(process.cwd(), "/reports/json")

const cucumberReporterOptions = {
    jsonFile: targetJson,
    output: htmlReports + "/cucumber_reporter.html",
    reportSuiteAsScenarios: true,
    theme: "bootstrap",
}

export class Reporter {
    static createHTMLReport() {
        try {
            reporter.generate(cucumberReporterOptions);
        } catch (err) {

        }
    }
}

如果您想继续使用 class 语法,您也可以将 jsonReportscucubmerReporterOptions 设为静态属性:

export class Reporter {
    static createHTMLReport() {
        try {
            reporter.generate(Reporter.cucumberReporterOptions);
        } catch (err) {

        }
    }
}

Reporter.jsonReports = path.join(process.cwd(), "/reports/json")

Reporter.cucumberReporterOptions = {
    jsonFile: targetJson,
    output: htmlReports + "/cucumber_reporter.html",
    reportSuiteAsScenarios: true,
    theme: "bootstrap",
}