So up until now, i have created classes and modules in node.js
the following way:
var fs = require('fs');
var animalModule = (function () {
/**
* Constructor initialize object
* @constructor
*/
var Animal = function (name) {
this.name = name;
};
Animal.prototype.print = function () {
console.log('Name is :'+ this.name);
};
return {
Animal: Animal
}
}());
module.exports = animalModule;
Now with ES6, you are able to make "actual" classes just like this:
class Animal{
constructor(name){
this.name = name ;
}
print(){
console.log('Name is :'+ this.name);
}
}
Now, first of all, i love this :) but it raises a question. How do you use this combined with node.js
's module structure?
Say you have a class where you wish to use a module for the sake of demonstration say you wish to use fs
so you create your file:
Animal.js
var fs = require('fs');
class Animal{
constructor(name){
this.name = name ;
}
print(){
console.log('Name is :'+ this.name);
}
}
Would this be the right way?
Also, how do you expose this class to other files within my node project? And would you still be able to extend this class if you're using it in a separate file?
I hope some of you will be able to answer these questions :)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…