我目前正在设计一个应用程序,并正在扩展一些类。下面是一个简短的示例代码,展示了它今天的样子,以及我想要去的地方(又名一个文件,多个类并导出它们+在中使用它们>main.js - 或任何其他)..
<小时/>今天
main.js
const UrgentTask = require('./urgentTask');
const Task = require('./task');
var ut = new UrgentTask({ name: "Some task", priority: "URGENT" });
var nt = new Task({ name: "Normal task" });
console.log(ut.toString());
console.log(nt.toString());
task.js
'use strict'
class Task {
constructor(data) {
this.name = data.name;
this.completed = false;
}
complete() {
console.log('completing task: ' + this.name);
this.completed = true;
}
save() {
console.log('Saving task: ' + this.name);
}
toString() {
return this.name + ' ' + this.completed;
}
}
module.exports = Task;
urgentTask.js
'use strict'
var Task = require('./task');
// Decorate "TASK"
class UrgentTask extends Task {
constructor(data) {
super(data);
this.priority = data.priority;
}
toString() {
return `[${this.priority}] ${super.toString()}`;
}
}
module.exports = UrgentTask;
<小时/>
我想要什么
main.js
const { Task, UrgentTask } = require('./task');
var ut = new UrgentTask({ name: "Some task", priority: "URGENT" });
var nt = new Task({ name: "Normal task" });
console.log(ut.toString());
console.log(nt.toString());
task.js
=> 理想情况下,这会导出两个类,但我不知道如何导出? 我已经尝试过的:
module.exports = Task;
module.exports = UrgentTask;
但这在 Node 中爆炸了。
最佳答案
WHAT I WOULD LIKE
const { Task, UrgentTask } = require('./task');
这是一个解构赋值,它将对象属性分配给离散绑定(bind)(在本例中为常量)。
所以你需要导出一个对象:
ES2015+ 语法(但使用 Node 模块,而不是 ES2015 模块):
module.exports = {Task, UrgentTask};
ES5 和更早的语法:
module.exports = {Task: Task, UrgentTask: UrgentTask};
实际上,默认情况下,exports
已经是一个对象,因此您也可以执行以下操作:
module.exports.Task = Task;
module.exports.UrgentTask = UrgentTask;
但是用新对象替换它也很好。
简单的非必需示例:
function getMyStuff() {
class Task { }
class UrgentTask extends Task { }
return {Task, UrgentTask};
}
const {Task, UrgentTask} = getMyStuff();
const ut = new UrgentTask();
console.log(ut instanceof UrgentTask); // true
console.log(ut instanceof Task); // true
NodeJS 示例:
mymodule.js
:
class Task { }
class UrgentTask extends Task { }
module.exports = {Task, UrgentTask};
myapp.js
:
const {Task, UrgentTask} = require("./mymodule.js");
const ut = new UrgentTask();
console.log(ut instanceof UrgentTask); // true
console.log(ut instanceof Task); // true
关于javascript - 来自同一 require(js 文件)的多个导出类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40301365/