简体   繁体   English

JavaScript Singleton和IntelliJ Idea

[英]JavaScript Singleton and IntelliJ Idea

I'm having trouble with IntelliJ Idea's code completion and syntax checking and JavaScript. 我在IntelliJ Idea的代码完成,语法检查和JavaScript方面遇到麻烦。

I have the following (simplified) code for a Singleton object: 我为Singleton对象提供了以下(简化)代码:

var MySingleton = new function() {
    var self = this;

    self.prop = "hello world";

    self.printHello = function() {
        console.log(self.prop);
    };
};

MySingleton.printHello();

The problem is, that IntelliJ complains at the last line about Unresolved function or method printHello() . 问题是,IntelliJ在最后一行抱怨Unresolved function or method printHello() It also will not suggest printHello when autocompleting from MySingleton. MySingleton.自动完成时,也不会建议printHello MySingleton. . The code itself works fine though. 代码本身可以正常工作。

I guess I have to either annotate or rewrite my code in a different style. 我想我必须注释或以其他样式重写代码。 But how? 但是如何?

I am using factory to get Singeltons in Javascript. 我正在使用工厂来获取Java语言中的Singeltons。

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();

It seems like the module pattern is close to what I want to do and is well supported by Idea's code indexing: 似乎模块模式已经接近我想要做的事情,并且得到了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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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