I have a class
class advertHandler {
constructor(projects) {
this.projects = projects;
}
getProject(name) {
return this.projects[name];
}
}
module.exports = new advertHandler(projects);
When I try to use it like this
const advertHandler = require('./advertHandler')(projectsArray);
advertHandler.getProject('test');
And it throws an exception, require is not a function
, but without a constructor, everything is fine, so the question is how to use the class constructor with require?
The constructor() method is a special method for creating and initializing objects created within a class. The constructor() method is called automatically when a class is initiated, and it has to have the exact name "constructor", in fact, if you do not have a constructor method, JavaScript will add an invisible and empty constructor method.
The module parameter (rather a keyword in a module in Node) refers to the object representing the current module. exports is a key of the module object, the corresponding value of which is an object. The default value of module.exports object is {} (empty object). You can check this by logging the value of module keyword inside any module.
There can be only one special method with the name "constructor" in a class. Having more than one occurrence of a constructor method in a class will throw a SyntaxError error. A constructor can use the super keyword to call the constructor of a parent class. If you do not specify a constructor method, a default constructor is used.
1 Definition and Usage. The constructor () method is a special method for creating and initializing objects created within a class. 2 Browser Support 3 Syntax 4 Technical Details 5 More Examples. To create a class inheritance, use the extends keyword. The super () method refers to the parent class. 6 Related Pages
It's not saying require
is not a function, it's saying require(...)
is not a function. :-) You're trying to call the result of require(...)
, but what you're exporting (an instance of advertHandler
) isn't a function. Also note that in advertHandler.js
, you're trying to use a global called projects
(on the last line); ideally, best not to have globals in NodeJS apps when you can avoid it.
You just want to export the class:
module.exports = advertHandler;
...and then probably require it before calling it:
const advertHandler = require('./advertHandler');
const handler = new advertHandler({test: "one"});
console.log(handler.getProject('test'));
E.g.:
advertHandler.js:
class advertHandler {
constructor(projects) {
this.projects = projects;
}
getProject(name) {
return this.projects[name];
}
}
module.exports = advertHandler;
app.js:
const advertHandler = require('./advertHandler');
const handler = new advertHandler({test: "one"});
console.log(handler.getProject('test'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With