Reputation: 1496
I'm a little confused about coding with classes in ES6. Suppose I want to create a simple library similar to JS. I create a module like so in my library.js:
const $ = (...args) => {
if (typeof args[0] === 'function') {
const docReadyFn = args[0];
document.addEventListener('DOMContentLoaded', docReadyFn);
}
}
module.exports = $;
I then require this file in index.js:
const $ = require('./library');
module.exports = $;
And use it in another file:
const $ = require('./library');
$(() => {
console.log('DOM ready!');
});
However, instead of doing const $ = (...args) => { ... }
I want to make a class with a constructor like this:
class Library {
constructor(...args) {
if (typeof args[0] === 'function') {
const docReadyFn = args[0];
document.addEventListener('DOMContentLoaded', docReadyFn);
}
}
}
module.exports = Library;
Is it wise to do it this way? And with classes I have to create a new instance with new Library(args)
, but with by exporting const $ = (...args) => { ... }
I can simply use $
without doing anything. No new instance or anything. How can I use classes to achieve the same thing as creating a const and exporting that and using it right away?
Upvotes: 0
Views: 159
Reputation: 665276
A class
must always be called with new
, and will create a new instance.
Your $
function does not create objects - it should not be a class
.
Upvotes: 2