i learning use ecmascript6 -styled classes in nodejs (7.7.3). have used kind of programming style:
//app.js var forecasthandler = require('./forecasthandler.js'); //forecasthandler.js class forecasthandler { constructor() {} } module.exports = new forecasthandler()
it has worked until now, because have pass parameters module.
//app.js var forecasthandler = require('./forecasthandler.js')(3600); //forecasthandler.js class forecasthandler { constructor(cacheupdatedelay) {} } module.exports = new forecasthandler(cacheupdatedelay)
i got error: referenceerror: cacheupdatedelay not defined. can pass parameter forecasthandler-module using es6 styled classes , creating object @ module.exports? if export class , create object in app.js, code works, it's syntax ugly.
//app.js var forecasthandlerclass = require('./forecasthandler.js'); var forecasthandler = new forecasthandlerclass(3600); //forecasthandler.js module.exports = forecasthandler
edit: better examples
module.exports = new forecasthandler(cacheupdatedelay)
the trouble code initialises object when code first run.
require('./forecasthandler.js')
means "execute code in forecasthandler.js
, give me exports
object. means js engine tries run new forecasthandler(cacheupdatedelay)
when there no cacheupdatedelay
created.
the simple way 1 provide. load class, try make new instance of it. if really want one-line it, can in app.js
:
var forecasthandler = new (require('./forecasthandler.js'))(3600);
there various other ways this. simplest involve not exporting class function.
for instance, in module file:
module.exports = cacheupdatedelay => new forecasthandler(cacheupdatedelay); // or module.exports = function(cacheupdatedelay) { return new forecasthandler(cacheupdatedelay); };
Comments
Post a Comment