到目前为止,我已经在 node.js
中创建了类和模块,方法如下:
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;
现在使用 ES6,您可以像这样创建“实际”类:
class Animal{
constructor(name){
this.name = name ;
}
print(){
console.log('Name is :'+ this.name);
}
}
现在,首先,我喜欢这个 :) 但它提出了一个问题。结合node.js
的模块结构如何使用?
假设您有一个类,您希望在其中使用模块以进行演示,假设您希望使用 fs
所以你创建你的文件:
Animal.js
var fs = require('fs');
class Animal{
constructor(name){
this.name = name ;
}
print(){
console.log('Name is :'+ this.name);
}
}
这是正确的方法吗?
另外,您如何将此类公开给我的 Node 项目中的其他文件?如果你在一个单独的文件中使用它,你还能扩展这个类吗?
我希望你们中的一些人能够回答这些问题:)
最佳答案
是的,您的示例可以正常工作。
至于公开你的类,你可以像其他任何东西一样export
一个类:
class Animal {...}
module.exports = Animal;
或更短的:
module.exports = class Animal {
};
一旦导入到另一个模块中,您就可以将其视为已在该文件中定义:
var Animal = require('./Animal');
class Cat extends Animal {
...
}
关于javascript - 带有 require 的 Node.js ES6 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42684177/