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

时间:2018-05-25 12:13:12

标签: javascript ecmascript-6 es6-class

我在类构造函数中声明了一个属性,并通过方法进行访问,这些方法被声明为' static',其中'这个'它无法访问。如何在静态方法中访问构造函数(类)变量?

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) {

        }
    }
}

1 个答案:

答案 0 :(得分:1)

如果您想继续使用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",
}