繁体   English   中英

无法在ES6类上调用静态函数

[英]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()我都会收到此工具提示:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM