Zyie
Zyie

Reputation: 154

Cannot read property of undefined in class

I'm new to javascript so can anyone help me figure out why this code is not working?

I have a class and it calls a cordova barcode scanning function. I've got an example that works, however I want to be able to separate out the function(result) and function(error) and use onSuccess(result) and onFailure(error).

I have no idea why this is happening so if anyone can help that would be great.

EDIT: so ive updated the code based on Stradosphere said however im still getting result is not defined errors.

Full error message:

Uncaught ReferenceError: result is not defined at barcodeScanner.scanBarcode (barcodeScanner.js:10) at HTMLButtonElement.myFunction (main.js:18)

var me = this;
class barcodeScanner {
    constructor() {
        this._barcodeResult = 0;
    }

    scanBarcode() {
        //THIS THROWS result is not defined error 
        cordova.plugins.barcodeScanner.scan(me.onSuccess(result), me.onFailure(error));

        //THIS WORKS
        cordova.plugins.barcodeScanner.scan(
            function (result) {
                me._barcodeResult = result.text;
                alert("Barcode Scanned:" + me._barcodeResult);        
            },
            function (error) {
                alert("Scanning failed: " + error);
            }
        );
    }

    onSuccess(result) {
        this._barcodeResult = result.text;
        alert("Barcode Scanned:" + this._barcodeResult);
    }

    onFailure(error) {
        alert("Scanning failed: " + error);
    }
}

Upvotes: 1

Views: 8475

Answers (2)

Mark
Mark

Reputation: 92440

Looking at the docs, it appears that cordova.plugins.barcodeScanner.scan() expects you to pass a function into it. But you are calling it like this:

 cordova.plugins.barcodeScanner.scan(me.onSuccess(result), me.onFailure(error));

This is passing the result of the function .onSuccess(result), but result is not defined, so you are getting an error. Additionally, you want this to be the class instance, but by defining me as this outside the class, me won't equal the class instance like you want it to. But you don't need it anyway.

Try passing functions in instead:

cordova.plugins.barcodeScanner.scan((result) => this.onSuccess(result),(error)=> this.onFailure(error))

Upvotes: 1

Stradosphere
Stradosphere

Reputation: 1285

Maybe a scope issue on your use of this. Try:

var me = this; //(put this at class level)
cordova.plugins.barcodeScanner.scan(me.onSuccess, me.onFailure);

Upvotes: 0

Related Questions