简体   繁体   English

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

[英]unable to call static function on ES6 class

I have a file called helpers.js in the 'helpers' folder. 我在'helpers'文件夹中有一个名为helpers.js的文件。 The contents are like below: 内容如下:

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;

Then in /helpers/user.js I want to get the helper's singleton instance. 然后在/helpers/user.js我想得到帮助者的单例实例。 This is my code: 这是我的代码:

const helpers  = require('../helpers').getSingleton();

or 要么

const Helpers  = require('../helpers');
const helpers  = Helpers.getSingleton();

The error I keep getting is: 我一直得到的错误是:

TypeError: require(...).getSingleton is not a function

or 要么

TypeError: Helpers.getSingleton is not a function

If I hover over Helpers in VSCode, I get this tooltip 如果我将鼠标悬停在VSCode中的Helpers上,我会收到此工具提示

助手工具提示

And, whenever I hover over getSingleton() I get this tooltip: 而且,每当我将鼠标悬停在getSingleton()我都会收到此工具提示:

getSingleton()工具提示

So the path is correct, but it still gives me the errors. 所以路径是正确的,但它仍然给我错误。

The easiest way to implement the singleton pattern in JavaScript is to just not export the class at all, eg 在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

or even better, since we aren't restricted to Java-like behavior, just skip the function entirely and do 甚至更好,因为我们不仅限于类似Java的行为,只需完全跳过该功能即可

class Helpers {}
module.exports = new Helpers();

// loaded with
var helpers = require('../helpers');

but then if all your module is exporting is a single instance of a class, there's very little reason to use a class in the first place. 随后如果所有模块输出是一个类的一个实例,有很少的原因首先使用的类。 You might as well do 你不妨这样做

exports.helperMethodOne = function(){};
exports.helperMethodTwo = function(){};
exports.helperMethodThree = function(){};

// loaded with
var helpers = require('../helpers');

or 要么

module.exports = {
  helperMethodOne() {},
  helperMethodTwo() {},
  helperMethodThree() {},
};

// loaded with
var helpers = require('../helpers');

Your require statement is wrong, but its hard to tell you precisely the right syntax without knowing your environment. 您的require语句是错误的,但很难在不了解您的环境的情况下准确地告诉您正确的语法。

const config = require('/path/to/file');

Is typical. 很典型。 So try: 所以尝试:

const Helpers = require('../helpers');

You wrote '../helpers.js' in your screenshot, not '../helpers' 你在截图中写了'../helpers.js' ,而不是'../helpers'

You get the error: 你得到错误:

TypeError: require(...).getSingleton is not a function TypeError:require(...)。getSingleton不是函数

Because require(...) resolves to something else, like null , and null.getSingleton is not a function. 因为require(...)解析为其他内容,如null ,而null.getSingleton不是函数。


Also, you cannot reference this meaninfully inside a static context. 此外,您无法在静态上下文中引用this含义。 this ought to only be used for class instances, not static members. this应该只用于类实例,而不是静态成员。

You can do something like this to use it as Singleton.getInstance() ; 您可以执行类似这样的操作将其用作Singleton.getInstance() ;

class Singleton {
    static instance = new Singleton();
    static getInstance = () => Singleton.instance;

    constructor() {
        throw new Error('Use Singleton.getInstance()');
    }
}

module.exports = Singleton;

or even something more sneaky and use it as new 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