Reputation: 8960
I have a JS class declared as such:
class Useful {
someFunction(index) {
//Does something with index
}
However I'm unsure what the best practice is to declare require variables such as var fs = require('fs')
and how to use it - namely:
var fs = require('fs')
be inside the class
declaration or outside itthis
Thanks.
UPDATE - following comments - is this correct
const fs = require('fs')
class Useful {
someFunction(index) {
//Does something with index
fs.writeFile(......)
}
Upvotes: 0
Views: 69
Reputation: 138427
A
class Useful {
someFunction(index) {
const fs = require("fs");
}
}
B
const fs = require("fs");
class Useful {
someFunction(index) {
}
}
Theres an important difference between these two: In A, fs will be loaded every time someFunction is called. This is bad for performance and has no real advantage. So use B.
Upvotes: 0
Reputation: 1283
1) All module require declarations should ideally be at the top of the file.
const useful = require('useful')
class foo ....
2) 'this' refers to the class itself and so you need to explicitly attach the module you just imported inside the class constructor as a class property if you need it like that
class Useful (importedModule) {
constructor(importedModule) { // constructor syntactic sugar
this.module = importedModule;
}
3) With es6 you can also import your modules with
import somethingUseful from 'module_or_./filePath_where_something_useful_is_kept'
4) with es6 let and const are much better alternatives to var.
Upvotes: 1