Javascript - Google闭包注释属性类型

时间:2014-01-19 19:22:58

标签: javascript google-closure-compiler

我有像这样的Javascript UI对象:

function MyUIElement() {
    div = document.createElement("div");
    div.id = "my_element_x";
    div.innerHTML = "whatever";
    ...

    this.hide = function() {
        div.style.display = "none";
    };

    this.show = function() {
        div.style.display = "block";
    };

    this.showData = function(data) {
        ...
    }

    this.div = div;
}

function addUIElement(element) {
    app_div.appendChild(element);
}

myElement = new MyUIElement();
addUIElement(myElement.div)

我注意到Closure编译器不知道myElement.div的类型,所以我为它添加了一个类型:

function MyUIElement = {
    /**
     * @type {Element}
     */
    div = document.createElement("div");
    div.id = "my_element_x";
    div.innerHTML = "whatever";
    ...

但它仍然不知道类型。我必须注释“this.div = div”才能识别出类型。

我只是想知道这种情况的最佳/常见解决方案是什么。我应该使用this.div来访问我的div以避免两次注释吗?还有其他方法我应该控制MyUIElement类的公共/私有变量吗?

1 个答案:

答案 0 :(得分:1)

您有几个语法错误。尝试删除全局变量div并更正函数声明(即function MyUIElement() {)。另外this.showData声明不正确。

function MyUIElement() {
    /**
     * @type {Element}
     */
    var div = document.createElement("div");
    div.id = "my_element_x";
    div.innerHTML = "whatever";

纠正这些问题,让我们正确编译:compileduncompiled

如果您正在使用高级编译(您从未指定过),则需要在编译器中为构造函数添加一些提示,并在this上将其视为可公开访问的变量

/**
 * some description
 * @expose
 * @constructor Necessary to specify that this is a constructor function
 */
var MyUIElement = function() {
    /** @expose expose means this is accessible to the public don't minimize the var name */
    var div = this.div = document.createElement("div");
    div.id = "my_element_x";
    div.innerHTML = "whatever";

    /** @expose */
    this.hide = function() {
        div.style.display = "none";
    };

    /** @expose */
    this.show = function() {
        div.style.display = "block";
    };

    /** @expose */
    this.showData = function(data) {

    }
}
var myElement = new MyUIElement();