Google Closure Compiler,如何优雅地处理JSC_INEXISTENT_PROPERTY? [英] Google Closure Compiler, how to handle JSC_INEXISTENT_PROPERTY gracefully?

查看:92
本文介绍了Google Closure Compiler,如何优雅地处理JSC_INEXISTENT_PROPERTY?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个使用return语句来公开公共类方法的设计模式。

I'm using a design pattern that uses the return statement to expose public class methods.

问题是:我在Closure编译器中收到很多 JSC_INEXISTENT_PROPERTY 警告高级模式,这使得检查实际上重要的警告变得困难。

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.

我使用的模式示例:

// ==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');

警告:

JSC_INEXISTENT_PROPERTY: Property myPublicFunc never defined on MyClass \
    at line 16 character 0
myClassInstance.myPublicFunc('Hello World');

输出(格式化):

(new function() {
    return {
        a: function(a) {
            console.log(a)
        }
    }
}).a("Hello World");

这很奇怪,因为Closure了解代码正在做什么并正确编译代码,重命名 myPublicFunc 始终为 a 。那为什么我会收到这个警告?我做错了吗?

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?

注意:我不想关闭这些警告,因为它也会隐藏我真正关心的警告。我也不想使用带引号的字符串或导出,因为我确实希望Closure压缩它们。

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.

推荐答案

您的函数注释不正确。它实际上不是构造函数,在这种情况下, new 关键字是不必要的。你的函数只返回一个带有 myPublicFunc 属性的匿名类型。

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.

这篇关于Google Closure Compiler,如何优雅地处理JSC_INEXISTENT_PROPERTY?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆