JavaScript Singleton and IntelliJ Idea

JavaScript Singleton and IntelliJ Idea

本文关键字:Idea IntelliJ and Singleton JavaScript      更新时间:2023-09-26

我在使用IntelliJ Idea的代码完成和语法检查以及JavaScript时遇到了麻烦。

我有以下(简化的)单例对象代码:

var MySingleton = new function() {
    var self = this;
    self.prop = "hello world";
    self.printHello = function() {
        console.log(self.prop);
    };
};
MySingleton.printHello();

问题是,IntelliJ在最后一行抱怨Unresolved function or method printHello()。当从MySingleton.自动补全时,它也不会建议使用printHello。代码本身工作得很好。

我想我必须以不同的风格注释或重写我的代码。但如何?

我使用factory在Javascript中获得singelton。

var factory = function(){
    this.singelton = null;
    /**
     * @return MySingleton
     */
    function singelton(){
        if(this.singelton==null){
            this.singelton = new MySingelton();
        }
        return this.singleton;
    }
}
var instance_of_my_singleton = factory.singelton();

似乎模块模式接近我想要做的,并且由Idea的代码索引很好地支持:

var MySingleton = (function () {
    var self = this;
    var prop = "hello world";
    function printHello () {
        console.log(self.prop);
    };
    // export public functions
    return {
        printHello: printHello
    };
})();
MySingleton.printHello();