【问题标题】:Exposing dynamically created functions on objects with closure compiler使用闭包编译器在对象上公开动态创建的函数
【发布时间】:2012-07-27 03:31:40
【问题描述】:

我正在尝试注释我的 javascript,以便闭包不会重命名所有符号,因为我也在使用 vanilla javascript。

/**
* @constructor
* @expose
* @type{foo}
*/

foo = function (el, args) {
"use strict";
var s = "Hello World";
/*
* @expose
* @this {foo}
* @type {function}
*/
this.introduce = function () {
    return s;
 };
};

但是,当我通过具有高级优化的闭包编译器运行它时生成的输出是

foo = function() {
 this.a = function() {
 return"Hello World"

} };

我如何要求闭包保留名称引入,因为这将从外部 javascript 调用。

【问题讨论】:

    标签: google-closure-compiler google-closure-library


    【解决方案1】:

    以下选项可用于防止闭包编译器重命名 符号:

    如果您不想在函数原型上定义方法,如您的 例如,您可以使用goog.exportSymbol 导出构造函数foo 并使用@expose 导出方法。

    /**
     * @param {Element} el
     * @param {...*} args
     * @constructor
     */
    var foo = function (el, args) {
      "use strict";
    
      /** @private */
      this.msg_ = "Hello World";
    
      /**
       * @this {foo}
       * @return {string}
       * @expose
       */
      this.introduce = function () {
        return this.msg_;
      };
    };
    goog.exportSymbol('foo', foo);
    

    通过在函数原型上定义方法,goog.exportSymbol可以 用于导出构造函数和方法名称。

    /**
     * @param {Element} el
     * @param {...*} args
     * @constructor
     */
    var foo = function (el, args) {
      "use strict";
    
      /** @private */
      this.msg_ = 'Hello World!';
    };
    goog.exportSymbol('foo', foo);
    
    /**
     * @return {string}
     */
    foo.prototype.introduce = function () {
      return this.msg_;
    };
    goog.exportSymbol('foo.prototype.introduce', foo.prototype.introduce);
    

    查看这些相关的 stackoverflow 问题:

    【讨论】:

    • 当我在原型方法上使用@expose 注释时,它可以正常工作而无需使用 goog.exportSymbol。然而,暴露注释似乎不适用于直接添加到对象而不是原型的函数。我想在前一种情况下使用它,这样我就可以使用闭包而不是尝试使用所有成员变量。
    • 答案已更新以解释 @expose 并提供使用直接在构造函数和函数原型上定义的方法的工作示例。
    • 不要使用@expose注解。它很脆。 groups.google.com/forum/#!msg/closure-compiler-discuss/…
    • @expose 现在已弃用。它被@nocollapse@export 取代。编译器将警告@expose 的任何使用。
    猜你喜欢
    • 2014-01-23
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多