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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With