使用闭包编译器在对象上公开动态创建的函数 [英] Exposing dynamically created functions on objects with closure compiler

查看:57
本文介绍了使用闭包编译器在对象上公开动态创建的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to annotate my javascript so that closure doesnt rename all the symbols since i am working with vanilla javascript as well.

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

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

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

However the generated output when i run it through the closure compiler with advanced optimization is

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

} };

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

How do i ask closure to preserve the name introduce since this will be called from an external javascript.

推荐答案

以下选项可用于防止Closure Compiler重命名 符号:

The following options may be used to prevent the Closure Compiler from renaming symbols:

  • @export (另请参见: goog.exportProperty )
  • 通过将符号存储在字符串引用的全局对象上来导出符号. 请参见导出要保留的符号
  • 在externs文件中定义一个接口并实现该接口(请参见下面的链接答案)
  • 报价属性
  • 注意: @expose已弃用
  • @export (also see: goog.exportSymbol or goog.exportProperty)
  • Export symbols by storing them on the global object referenced by a string. See Export the Symbols You Want to Keep
  • Define an interface in an externs file and implement the interface (see linked answers below)
  • Quote properties
  • Note: @expose has been deprecated

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

If you do not want to define methods on the function prototype as shown in your example, then you could export the constructor foo with goog.exportSymbol and use @expose to export methods.

/**
 * @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可以是 用于导出构造函数和方法名称.

By defining methods on the function prototype, goog.exportSymbol can be used to export both the constructor as well as method names.

/**
 * @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问题:

See these related stackoverflow questions:

这篇关于使用闭包编译器在对象上公开动态创建的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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