Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

babel compile es6 class, function not defined

Babel is compiling my es6 class so the constructor is a function by itself and the method in the class becomes the class declaration.

This is causing any function calls in the constructors to be undefined.

Before:

class myClass {
    constructor() {
        myMethod();
    } // END constructor

    myMethod() {
        console.log("myMethod");
    } 
} // END myClass

After:

var myClass = function () {
    function myClass() {
        _classCallCheck(this, myClass);
        myMethod(); // undefined function
    } // END constructor

    _createClass(myClass, [{
        key: 'myMethod',
        value: function myMethod() { 
            console.log("myMethod");
        } // END myMethod()
    }]);

    return myClass;
}(); // END myClass

exports.default = myClass;

Appreciate any help in this

like image 249
appthat Avatar asked Feb 12 '16 23:02

appthat


1 Answers

You need this.myMethod() in ES6 class constructor and methods.

class myClass {
    constructor() {
        this.myMethod();
    } // END constructor

    myMethod() {
        console.log("myMethod");
    }
} // END myClass

myMethod() calls a function named myMethod outside of the class.

function myMethod() {
    console.log("external function!");
}

class myClass {
    constructor() {
        myMethod();
    } // END constructor

    myMethod() {
        console.log("myMethod");
    }
} // END myClass

JavaScript's method is just an Object's property that is a function. You need obj.prop to access a property. In class constructor and methods, this points to the instance itself.

like image 84
Shuhei Kagawa Avatar answered Nov 14 '22 06:11

Shuhei Kagawa