我在“helpers”文件夹中有一个名为 helpers.js
的文件。内容如下:
class Helpers {
constructor(config) {
if (this._singleton) {
throw new Error('A singleton has already been created.');
}
this._singleton = this;
}
/**
* Gets the singleton object.
* @returns {Helpers}
*/
static getSingleton() {
return this._singleton;
}
}
module.exports = Helpers;
然后在 /helpers/user.js
中,我想获取助手的单例实例。
这是我的代码:
const helpers = require('../helpers').getSingleton();
或
const Helpers = require('../helpers');
const helpers = Helpers.getSingleton();
我不断收到的错误是:
TypeError: require(...).getSingleton is not a function
或
TypeError: Helpers.getSingleton is not a function
如果我将鼠标悬停在 VSCode 中的 Helpers
上,我会得到这个工具提示
而且,每当我将鼠标悬停在 getSingleton()
上时,我都会得到这个工具提示:
所以路径是正确的,但它仍然给我错误。
最佳答案
在 JavaScript 中实现单例模式的最简单方法是根本不导出类,例如
class Helpers {}
let helper;
module.exports = function() {
if (!helper) helpers = new Helpers();
return helper;
};
// loaded with
var helpers = require('../helpers')(); // note the extra () to call it
甚至更好,因为我们不局限于类似 Java 的行为,只需完全跳过该函数并执行
class Helpers {}
module.exports = new Helpers();
// loaded with
var helpers = require('../helpers');
但是然后如果您的所有模块导出的都是类的单个实例,那么一开始就没有理由使用类。你也可以这样做
exports.helperMethodOne = function(){};
exports.helperMethodTwo = function(){};
exports.helperMethodThree = function(){};
// loaded with
var helpers = require('../helpers');
或
module.exports = {
helperMethodOne() {},
helperMethodTwo() {},
helperMethodThree() {},
};
// loaded with
var helpers = require('../helpers');
关于javascript - 无法在 ES6 类上调用静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47039542/