我创建的非常简单的模块是为了测试这项工作的可行性。这是 SPServerApp.ts
的开头:
class SPServerApp {
public AllUsersDict: any;
public AllRoomsDict: any;
constructor () {
this.AllUsersDict = {};
this.AllRoomsDict = {};
}
}
module.exports = SPServerApp();
然后在我的应用程序中,我有这个 require 语句:
var serverapp = require('./SPServerApp');
然后我尝试像这样访问其中一本词典:
serverapp.AllUsersDict.hasOwnProperty(nickname)
但出现错误:
类型错误:无法读取未定义的属性“hasOwnProperty”
有人能看到我在这里做错了什么吗?
谢谢,E。
最佳答案
问题是您在调用构造函数时忘记了“new”关键字。该行应为:
module.exports = new SPServerApp();
如果您不使用new,您的构造函数将被视为普通函数,并且只会返回未定义的值(因为您没有显式返回任何内容)。此外,“this”不会指向您在构造函数中所期望的内容。
在 Node 中省略 new 实际上很常见。但要使其发挥作用,您必须明确防止构造函数中的 new 调用,如下所示:
constructor () {
if (! (this instanceof SPServerApp)) {
return new SPServerApp();
}
this.AllUsersDict = {};
this.AllRoomsDict = {};
}
顺便说一句,在 TypeScript 中你还可以使用模块语法。 TS 编译器会将其转换为export/require 语句。使用 ES6 样式模块,您的示例将如下所示:
export class SPServerApp {
public AllUsersDict: any;
public AllRoomsDict: any;
constructor () {
this.AllUsersDict = {};
this.AllRoomsDict = {};
}
}
export var serverapp = new SPServerApp();
在您刚刚导入的其他 TS 文件中:
import { serverapp } from './SPServerApp';
serverapp.AllUsersDict.hasOwnProperty('something');
关于node.js - 如何使用 Typescript 创建 Node.js 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38937963/