在 TypeScript 中,Class 有private constructor()
,所以我们可以很容易地创建单吨模式类,如下所示。
class Singleton {
static instance = new Singleton();
prop = 0;
private constructor() {}
}
Singleton.instance.prop; // 0
当我在没有 TSC 的情况下使用 Babel 构建此 TypeScript 代码时,引发错误Singleton is not a constructor
. 我该怎么办?
我正在回答这个问题,因为几个小时内没有其他答案。我不是在直接回答问题,但它也可以是关于解决方案本身的答案。
在 Node.js 世界中,制作额外的单例是没有意义的。为什么?每个文件都是独立的。
如果您有如下所示的文件(模块(:
class Singleton {
constructor() {}
}
exports.instance = new Singleton();
然后,您只能访问实例,该实例基本上是单例。真的没有办法访问其他任何东西。
我无法重现您的问题。 编译你的代码(使用控制台.log围绕最后一行(,用这个babelrc:
{
"presets": [
"@babel/preset-env",
"@babel/preset-typescript"
],
"plugins": [
"@babel/proposal-class-properties",
"@babel/proposal-object-rest-spread"
]
}
生成以下代码,该代码按预期运行:
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var Singleton = function Singleton() {
_classCallCheck(this, Singleton);
_defineProperty(this, "prop", 0);
};
_defineProperty(Singleton, "instance", new Singleton());
console.log(Singleton.instance.prop); // 0