[英]unable to call static function on ES6 class
我在'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');
您的require語句是錯誤的,但很難在不了解您的環境的情況下准確地告訴您正確的語法。
const config = require('/path/to/file');
很典型。 所以嘗試:
const Helpers = require('../helpers');
你在截圖中寫了'../helpers.js'
,而不是'../helpers'
你得到錯誤:
TypeError:require(...)。getSingleton不是函數
因為require(...)
解析為其他內容,如null
,而null.getSingleton
不是函數。
此外,您無法在靜態上下文中引用this
含義。 this
應該只用於類實例,而不是靜態成員。
您可以執行類似這樣的操作將其用作Singleton.getInstance()
;
class Singleton {
static instance = new Singleton();
static getInstance = () => Singleton.instance;
constructor() {
throw new Error('Use Singleton.getInstance()');
}
}
module.exports = Singleton;
甚至更偷偷摸摸的東西,並將其用作new Singleton()
class Singleton {
static instance;
constructor() {
if (!Singleton.instance) {
Singleton.instance = this;
}
return Singleton.instance;
}
}
module.exports = Singleton;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.