babel compile es6 class, function not defined
11,483
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.
Author by
appthat
Updated on June 06, 2022Comments
-
appthat almost 2 years
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
-
appthat over 8 yearsthanks for the help, I tried that originally in the constructor, adding this. to method declaration is not mentioned in es6 docs and babel through a syntax error 'unexpected token' on that as well. Also tried myMethod: function() {}, same result. Could provide code sample, so I can see what exactly you are talking about?
-
appthat over 8 yearsThanks that was in fact part of my problem, the other problem I was overlooking is that I was trying to access myMethod inside a callback anonymous function. removing the anonymous func wrapper and using this.myMethod.bind(this) fixed the problem once and for all
-
Shuhei Kagawa over 8 yearsIf you are using ES6, Arrow Function (
() => {}
) is also handy. Inside it,this
refers to the same object that its outer scope'sthis
refers to.class Something { constructor() { someElement.addEventListener('click', () => { this.myMethod(); /* 'this' refers to the instance! */ }); } }