gpt4 book ai didi

javascript - 链接需求的正确方法

转载 作者:行者123 更新时间:2023-12-01 03:19:31 25 4
gpt4 key购买 nike

我是 Node 和 npm 的新手,所以感谢您的耐心配合。

我想打包/模块化一系列从基类继承的类(在单独的文件中),并且所有类都应该对最终用户/程序员可见。换句话说,我想保留以前的要求,以便我拥有最终用户可以要求获得所有内容的主对象。 require('Event') 还需要用户/程序员的 Item。

"use strict";
const Item = require('./Item');

module.exports = class Event extends Item {
constructor() {
super();
this.TypeName = 'Event';
this.JSON = '{}';
}

static Bind(service, eventId) {
return new Event();
}
}

"use strict";

module.exports = class Item {
constructor() {
this.TypeName = 'Item';
this.JSON = '{}';
}

static Bind(service, itemId) {
return new Item();
}
}

感谢您的帮助!

最佳答案

如果您想从一个模块导出多个内容,那么您可以导出一个父对象,并且您想要导出的每个内容都是该对象的一个​​属性。这不是“链接”,因为实际上不存在从模块导出多个顶级项目的东西。

module.exports = {
Event, Item
};

class Item {
constructor() {
this.TypeName = 'Item';
this.JSON = '{}';
}

static Bind(service, itemId) {
return new Item();
}
}
class Event extends Item {
constructor() {
super();
this.TypeName = 'Event';
this.JSON = '{}';
}

static Bind(service, eventId) {
return new Event();
}
}

然后,使用此模块的人会这样做:

const m = require('myModule');
let item1 = new m.Item();
let event1 = new m.Event();

或者,您可以将它们分配给模块内的顶级变量:

const {Item, Event} = require('myModule');
let item1 = new Item();
let event1 = new Event();
<小时/>

如果您有多个类,每个类都在自己的文件中,并且您希望能够使用一个 require() 语句加载所有类,那么您可以创建一个主文件来执行 require() 每个单独的文件并将它们组合成一个导出的对象。然后,当您想导入所有这些时,您只需在主文件中进行 require 即可。

node.js 模块的设计使得您可以 require() 该模块中您需要的所有内容,并且您可以在每个想要使用某些内容的模块中执行此操作。这增强了模块的可重用性或可共享性,因为每个模块独立导入它需要的东西。在任何其他模块工作之前,您不需要将所有这些全局状态导入到某个地方。相反,每个模块都是自描述的。这也使得处理模块的人员更加清楚它所依赖的内容,因为它所依赖的所有内容都有一个 require() 语句。对于来自不同环境的人来说,这似乎有点额外的输入,在这些环境中,您可能只需将某些内容导入到全局命名空间中(并且需要更多的输入),但这样做是有充分理由的,而且老实说,它并没有这样做。很快就会习惯它,然后您就可以享受到这样做的一些好处。

关于javascript - 链接需求的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45316935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com