I’m using a design pattern that uses the return statement to expose public class methods.
Problem is: I’m getting a lot of JSC_INEXISTENT_PROPERTY warnings in Closure Compiler’s Advanced mode, which makes it difficult to check the warnings that actually matter.
Example of the pattern I use:
// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// ==/ClosureCompiler==
/**
* @constructor
*/
var MyClass = function() {
var someFunc = function(myString) {
console.log(myString);
}
return {
myPublicFunc: someFunc
};
}
var myClassInstance = new MyClass();
myClassInstance.myPublicFunc('Hello World');
Warnings:
JSC_INEXISTENT_PROPERTY: Property myPublicFunc never defined on MyClass \
at line 16 character 0
myClassInstance.myPublicFunc('Hello World');
Output (formatted):
(new function() {
return {
a: function(a) {
console.log(a)
}
}
}).a("Hello World");
Which is weird, because Closure understood what the code was doing and compiled the code correctly, renaming myPublicFunc consistently to a. So why did I get this warning? Am I doing something wrong?
Note: I do not want to turn off these warnings because it would also hide warnings I actually care about. I also do not want to use quoted strings or exports because I do want Closure to compress these.
Your function is annotated incorrectly. It’s actually not a constructor and in this case the
newkeyword is unnecessary. Your function simply returns an anonymous type with amyPublicFuncproperty.To annotate such a pattern, you would use the record type:
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.