mmar
mmar

Reputation: 2020

how to declare an object in javascript es6 class constructor

I declared a property in class constructor and accessing through methods, which is declared as 'static', with 'this' and it is not accessible. How to get access to constructor (class) variables inside static methods?

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

        }
    }
}

Updated:

As per "@CodingIntrigue", I have done like this in 'reporter.js' file and called the method as Reporter.createHTMLReport() in my config file and its working as expected. But not sure if this is best practice.

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

        }
    }
}

Upvotes: 0

Views: 90

Answers (1)

CodingIntrigue
CodingIntrigue

Reputation: 78525

If you want to continue using class syntax, you can just make jsonReports and cucubmerReporterOptions static properties too:

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",
}

Upvotes: 1

Related Questions