简体   繁体   中英

I am getting: Cannot call method 'someMethodName' of undefined when trying to access an object in a javascript clas

I am almost new to JavaScript, and I am trying to access an object within a class. This is my class definition in a file called analysis.po.js:

var AnalysisPage = function () {
    (some  code here)
    this.getSpousesCreditBureau = function() {
        return {
            pdScore: getSpousesCreditBureauElement('pdScore'),
            qualification: getSpousesCreditBureauElement('qualification'),
            estimatedFee: getSpousesCreditBureauElement('estimatedFee'),
            currentDebt:  getSpousesCreditBureauElement('currentDebt'),
            maxDebt: getSpousesCreditBureauElement('maxDebt'),
            arrears: getSpousesCreditBureauElement('arrears'),
            segment: getSpousesCreditBureauElement('segment'),
            bpGlobalRisk: getSpousesCreditBureauElement('bpGlobalRisk'),
            groupGlobalRisk:  getSpousesCreditBureauElement('groupGlobalRisk')
        };
    };
    (some other code here)
};
module.exports = new AnalysisPage();

This is the piece of code where I try to get the object getSpousesCreditBerauElement in another file called analysis.spec.js:

var App = require('../app.po.js'),
    Util = require('../util.js'),
    AnalysisPage = require('./analysis.po.js'),
    AnalysisData = require('./analysis.data.js');
(some code here)
var analysis = new AnalysisPage();
Util.verifyElementsAreDisplayed(analysis.getSpousesCreditBureau());
(some other code here)

The error I am getting is: Cannot call method 'getSpousesCreditBureau' of undefined

You're not actually exporting AnalysisPage and you're not calling it correctly.


Export the class with:

module.exports = AnalysisPage;

In comparison

module.exports = new AnalysisPage();

Exports an instance of the class.


The right way to call it is then:

var instance = new AnalysisPage();
Util.verifyElementsAreDisplayed(instance.getSpousesCreditBureau());

(Original question has been modified, code was:)

var analysis = new AnalysisPage();
Util.verifyElementsAreDisplayed(AnalysisPage.getSpousesCreditBureau());

You can export just the instance, in that case call it like:

var instance = require('./analysis.po.js');
Util.verifyElementsAreDisplayed(instance.getSpousesCreditBureau());

So no new anywhere.

Did you tried:

var analysis = new AnalysisPage();
Util.verifyElementsAreDisplayed(analysis.getSpousesCreditBureau());

When you access the method like this AnalysisPage.getSpousesCreditBureau() you are not accessing the instance, but the class definition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM