Nat*_*der 32 javascript node.js node-modules
目前,我在自己的文件中有4个子类.我要求他们都在同一个文件中.我想知道我是否可以在一个模块中包含所有这四个类.目前,我正在这样导入它们
var Jack = require('./Jack.js');
var JackInstance = new Jack();
var Jones = require('./Jones.js');
var JonesInstance = new Jones();
Run Code Online (Sandbox Code Playgroud)
我想像这样导入它们
var People = require('./People.js');
var JackInstance = new People.Jack();
Run Code Online (Sandbox Code Playgroud)
甚至
var Jack = require('./People.js').Jack;
var JackInstance = new Jack();
Run Code Online (Sandbox Code Playgroud)
我的课程定义如此
class Jack{
//Memeber variables, functions, etc
}
module.exports = Jack;
Run Code Online (Sandbox Code Playgroud)
Muk*_*rma 79
是的,您可以导出多个类.
例如People.js
class Jack{
//Member variables, functions, etc
}
class John{
//Member variables, functions, etc
}
module.exports = {
Jack : Jack,
John : John
}
Run Code Online (Sandbox Code Playgroud)
并且,您可以按照正确的提及访问这些类.
var People = require('./People.js');
var JackInstance = new People.Jack();
var JohnInstance = new People.John();
Run Code Online (Sandbox Code Playgroud)
Dam*_*nic 66
您也可以使用解构分配(本机从Node.js v6.0.0开始支持)以较短的形式执行此操作:
// people.js
class Jack {
// ...
}
class John {
// ...
}
module.exports = { Jack, John }
Run Code Online (Sandbox Code Playgroud)
输入:
// index.js
const { Jack, John } = require('./people.js');
Run Code Online (Sandbox Code Playgroud)
或者甚至像这样,如果你想要别名需要分配:
// index.js
const {
Jack: personJack, John: personJohn,
} = require('./people.js');
Run Code Online (Sandbox Code Playgroud)
在后一种情况下personJack,personJohn将参考您的课程.
一句警告:
从某种意义上讲,解构可能会产生意外错误.忘记花括号export或意外包含它们相对容易require.
| 归档时间: |
|
| 查看次数: |
29980 次 |
| 最近记录: |