I have this sample class sync.js as a module somewhere on my project.
'use strict';
export default class Sync{
constructor(dbConnection){
this.dbConnection = dbConnection;
}
test(){
return "This is a test " + this.dbConnection;
}
}
Then somewhere on my controller I am using this class as :
'use strict';
import Sync from '../../path/to/module'; // <-- works fine
const sync = new Sync('CONNECTION!'); // <-- meh
console.log(sync.test());
I was expecting something like this to be logged on the console This is a test CONNECTION!. But instead I am getting this error. TypeError: object is not a constructor
What did I do wrong?
By the way if I removed the line const sync = new Sync('CONNECTION!'); and changed console.log() to console.log(Sync.test()); the output This is a test undefined is printed which is kind of what I expected. But what's wrong with my instatiation?
WTF?
Edit
Guys I think I found the problem, based on @JLRishe and rem035 pointed out, it was returning the instance of the class not the class itself. In fact there is an index.js that imports the './sync' js file and exporting is as export default new Sync();. Here's the whole index.js.
'use strict';
import Sync from './sync';
export default new Sync(); // <-- potential prodigal code
The module tree looks like this.
module
|
|_ lib
| |_ index.js // this is the index.js I am talking about
| |_ sync.js
|
|_ index.js // the entry point, contains just `module.exports = require('./lib');`
Now. How do I export export default new Sync(); without doing new?
newaccidentally in your default export? The code you've shown us does export the class, not an instance.Syncvariable is an instance of theSyncclass rather than the class itself. Couldn't say why though. Are you showing us the full contents, unmodified, of your sync.js file?Sync = new Syncsomewhere in there?