Reputation: 1319
I've been learning some React, and I have been using ES6 classes to write my class-based components. I'm working on a little Node project, and none of this syntax is working.
class Handler {
handleReq = () => {
this.ctx = ctx;
};
testFunc = async () => {
};
}
export default (HandleReq = Handler.prototype.handleReq);
What is wrong with this syntax? Does it not run in Node? I had to install esm
to get the import/export syntax working correctly, but this still fails to compile.
Upvotes: 1
Views: 66
Reputation: 6529
As others have pointed out, class fields aren't yet part of ES6 syntax without transpiling. If you want to avoid a build step, the equivalent node syntax is:
// import someImport from './some-import' is invalid, instead use:
const someImport = require('./some-import');
class Handler {
constructor() {
this.handleReq = this.handleReq.bind(this);
this.testFunc = this.testFunc.bind(this);
}
handleReq() {
this.ctx = ctx; // Where is ctx coming from?
}
async testFunc() {
}
}
// export default Handler.prototype.handleReq is invalid, instead use:
module.exports = Handler.prototype.handleReq;
Upvotes: 0
Reputation: 138267
Class Fields are still in the proposal phase (stage 3 already, so they will become part of the language soon). That means that some runtimes might support them already, however they don't have to yet. To use proposals today reliably you have to transpile it down with BabelJS.
That would transpile your code to the following ES6:
class Handler {
constructor() {
this.handleReq = () => {
this.ctx = ctx;
};
this.testFunc = async () => {
};
}
}
therefore these methods actually only exist on an instance after construction and not on Handler.prototype
.
Upvotes: 2