JSDoc for special singleton pattern

2019-07-08 02:48发布

问题:

I have a special JS singleton prototype function.

Pattern looks more or less like example below. Work fine and do the job, but sadly PhpStorm is totally blind regarding to auto-completion and other useful things.

How to tell the IDE using JSDoc that new Item will result in the end in new object build with ItemPrototype, so new Item(1).getId() will point to the right place in the code?

Thanks in advance for your time.

var Item = (function(){
    var singletonCollection = {};

    var ItemPrototype = function(id){

        this.getId = function() {
            return id;
        };

        return this;
    };

    var Constructor = function(id){
        if (! (id in singletonCollection)) {
            singletonCollection[id] = new ItemPrototype(id);
        }

        return singletonCollection[id];
    };

    return Constructor;
})();

回答1:

You can try the following:

/**
 * A description here
 * @class
 * @name Item
 */
var Item = (function(){
    var singletonCollection = {};

    var ItemPrototype = function(id){
        /**
         * method description
         * @name Item#getId
         */
        this.getId = function() {
            return id;
        };

        return this;
    };

    var Constructor = function(id){
        if (! (id in singletonCollection)) {
            singletonCollection[id] = new ItemPrototype(id);
        }

        return singletonCollection[id];
    };

    return Constructor;
})();