Google Closure Compiler, how to handle JSC_INEXISTENT_PROPERTY gracefully?

孤人 提交于 2019-12-06 09:38:16

Your function is annotated incorrectly. It's actually not a constructor and in this case the new keyword is unnecessary. Your function simply returns an anonymous type with a myPublicFunc property.

To annotate such a pattern, you would use the record type:

/** @return {{myPublicFunc: function(string) }} */
var MyClass = function() {

    var someFunc = function(myString) {
        console.log(myString);
    }

    return {
        myPublicFunc: someFunc
    };
};

var myClassInstance = MyClass(); // new keyword not needed
myClassInstance.myPublicFunc('Hello World');

Another annotation option is to create an interface and type-cast the returned object to be that interface. This option would be useful when multiple functions return an object that conforms to the same interface.

You can also use:

/** @type {function(new:{myPublicFunc: function(string)} )} */
var MyClass = function() {...

The function can be called with "new" but doesn't return an instance of "MyClass".

Adding

MyClass.prototype.myPublicFunc = null;

would solve the problem though I don't know whether this is the best solution.

I don't really know how the compiler works, but I could imagine that if you have a constructor function, it expects instance properties to be assigned to this inside the constructor or to MyClass.prototype.

If you remove the @constructor annotation and omit new, then there is not warning (but the compiled code is only console.log("Hello World");.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!